Ways to add javascript files dynamically in a page
Asked Answered
S

9

38

I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.

For example, I would like to include my js files like,

<script src="single.js?files=first.js,second.js,third.js..."></script>

How can I do that in an efficient manner?

Straggle answered 22/4, 2011 at 2:5 Comment(7)
Why negative voting?What's wrong with it?Straggle
@Hoque - it looks like someone is going through the question page and downvoting everything; there's at least 5 questions in a row with -1 or lower. I'm guessing a moderator could verify this...Igraine
Agree, I was also curious what's happening. Seems like some spammer is having a fun. So... +1 to compensate.Entomostracan
I wonder there are three arswers here, but I am getting only two. What is going on?Straggle
@Hoque - one was spam and deleted. I believe the answer count is cached or possibly just includes deleted answers (i.e. a bug).Igraine
You might want to investigate RequireJS or LabJSSosa
Possible duplicate of JQuery to load Javascript file dynamicallyDike
R
46

To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

i hope its use full

Reposit answered 23/4, 2011 at 6:43 Comment(5)
Thank you so much for your effort. This is like adding script one by one.Straggle
What's the browser support?Brownedoff
u need to add document.body.appendChild(fileref); to make it work in a browserVocalist
Be aware that the files may not load (and run) in the exact order you call them in.Supporting
document.getElementsByTagName("head")[0].appendChild(fileref) is not working if you have some document.ready() works inline. $("head").append(fileref); works great for me, although it needs jquery.min.js inline reference.Eer
E
13

You can use the jQuery.getScript() function... I think it will be much easier to you with this to include a JavaScript .js file.

Here is the reference.

Enwreathe answered 22/4, 2011 at 3:25 Comment(1)
I think that's the text I'm going to use for all my links on SO.Bitters
E
4

Following the advice of Salaman A's comments, I found how Google does it now with Analytics: https://developers.google.com/analytics/devguides/collection/gajs/asyncTracking

And here is a more generic version of the same code:

(function() {
    var s = document.createElement('script'); // Create a script element
    s.type = "text/javascript";               // optional in html5
    s.async = true;                           // asynchronous? true/false
    s.src = "//example.com/your_script.js"; 
    var fs = document.getElementsByTagName('script')[0];  // Get the first script
    fs.parentNode.insertBefore(s, fs);
})();
Election answered 17/9, 2014 at 18:30 Comment(0)
R
3

EDIT: DON'T USE THIS METHOD - I wrote this anwer a decade ago!

Leaving it here purely for posterity.


there are many different ways, but the way Google loads additional scripts is like this:

function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
}

This is taken directly from Google maps loader.

Writing a script tag directly to the document is the simplest and most efficient way.

Randirandie answered 23/4, 2011 at 6:36 Comment(7)
Google itself does not recommend it anymore :) for example they've changed the recommended way of adding google analytics code to websites.Branton
could you provide a link to back that up as all google's apis are loaded this way, even code.google.com/apis/loaderRandirandie
There you go: Using the Traditional Snippet. Read the introductory paragraph that says we recommend that you use the default tracking code snippet, described in Tracking Sites. The legacy script (script loader to be more precise) uses document.write, the updated script uses document.createElement. Here is another interesting read: Avoid document.writeBranton
interesting read. you only really gain when you load scripts asynchronously this way, which is fine if you use a callback. I guess it depends if you need your scripts loaded in a curtain order.Randirandie
LOL thanks for the downvote 3 1/2 years after the answer - unsurprisingly things have moved on since I wrote this answer.Randirandie
@Randirandie you need to update every single answer you post on a regular basis!! Everybody else does it hahaha :PPericynthion
This blows away any other HTML on the page... not goodFallal
S
2

Create a script tag, set the URL, add it to the document:

var script = document.createElement("script");
script.src = "https://example.com/your_script.js"; 
document.body.appendChild(script);

That's it. There are too many overly complicated answers on this page for such a simple task.

If you're using modern JavaScript, you can use dynamic importing with a syntax like await import(...). That's out of the scope of this answer, but you can read more about that here.

Stenography answered 9/7, 2020 at 14:31 Comment(1)
why append to body and not to head?Chalco
T
1

To add a new javascript file dynamically:

function includeJS(jsFile) {
    $('head').append($('<script>').attr('type', 'text/javascript').attr('src', jsFile));
}


// Pick a JS to load
if ($.browser.msie) {
    includeJS('first.js');
} else {
    includeJS('second.js');
}
includeJS('third.js');
Tonatonal answered 22/4, 2011 at 2:18 Comment(1)
If you have jQuery loaded, just use jQuery.getScript().Ligurian
B
1

I've seen what the scriptaculous loader does. What it does is that it goes through all script tags in the document to find the one that loaded itself, e.g:

<script src="/path/to/single.js?files=first.js,second.js,third.js"></script>

Then it parses the querystring used inside the src attribute and dynamically create additional script tags for each script file. At the same time it also parses the path of the base script (/path/to/single.js) and uses the same path to load dependency files (e.g. /path/to/first.js).

You can create your own script loader like this. In vanilla javascript, you can use the following functions:

Anand Thangappan has posted a solution that uses these functions. If you're using a framework such as jQuery or MooTools then both provide their own implementations of dynamically loading JsvaScript.

Finally, there is a server side solution for your problem. Look at minify -- Combines and minifies multiple CSS or JavaScript files into a single download.

Branton answered 23/4, 2011 at 6:58 Comment(0)
E
1

document.getElementsByTagName("head")[0].appendChild(fileref‌​) is not working if you have some document.ready() works inline. $("head").append(fileref); works great for me, although it needs jquery.min.js inline reference.

<head>
    <!-- Meta, title, CSS, favicons, etc. -->
    <script src="script/jquery.min.js"></script>
    <script src="script/master_load.js"></script>
    <script>
        load_master_css();
        load_master_js();
    </script>
</head>

and master_load.js :

function loadjscssfile(filename) {
    if (filename.substr(filename.length - 4) == ".css") { // 'endsWith' is not IE supported.
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("href", filename)
        //fileref.setAttribute("type", "text/css")
    }
    else if (filename.substr(filename.length - 3) == ".js") {
        var fileref = document.createElement('script')
        fileref.setAttribute("src", filename)
        //fileref.setAttribute("type", "text/javascript")
    }
    $("head").append(fileref);
}
function load_master_css() {
    loadjscssfile("css/bootstrap.min.css");
    // bunch of css files
}
function load_master_js() {
    loadjscssfile("script/bootstrap.min.js");
    // bunch of js files
}
Eer answered 11/3, 2017 at 7:43 Comment(0)
A
0

We can quickly extend this so that a callback can be performed once the script is added.

function loadjscssfile(filename, filetype, callback){
    if (typeof fileref!="undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);
        callback();
    }
}
Amabil answered 21/7, 2014 at 17:9 Comment(2)
I doubt this works at all... You pass filename and filetype which you don't use and use fileref which you don't declare...Pericynthion
Sorry, my comment was in reference to Anand Thangappan's answer above. I though i had made this a comment on that, not a new answer.Amabil

© 2022 - 2024 — McMap. All rights reserved.