views:

74

answers:

3

What I'm trying to do is dynamically include one or more js files from within Javascript. I know there are a bunch of techniques for this, but I'm looking for a solution that follows these rules:

1) Not use any JS frameworks or libraries (jQuery, Prototype, etc).

2) The script should halt execution until the external js file is completely loaded and parsed by the browser.

The rational behind #2 is the external js file will include function definitions that need to be used immediately after the script is included. Most of the time the browser hasn't had time to parse the js file before I start calling those functions.

I don't mind using a callback to know when the script is finished loading, but:

1) I don't know ahead of time how many scripts are going to be dynamically included, so I don't want and can't write a bunch of nested callbacks. I just need to know when they're all finished loading.

2) I'm wording that trying to use some kind of "load" event to fire the callback might not work if the browser has cached the JavaScript.

Edit I should have mentioned from the start that this is for a plugin system, but I wanted to keep my question/answer generic enough to be helpful to other people.

Users would define which plugins they want to load in an array.

plugins = [ 'FooPlugin', 'BarPlugin' ];

I would then loop through the array, and load the js script for each plugin:

for(var i = 0; i < plugins.length; i++) {
    loadScript('plugins/' + plugins[i] + '.js');
}

Each plugin pushes itself onto the loaded_plugins array (This is an example of FooPlugin.js)

load_plugins.push({
    name: 'FooPlugin',
    // Other plugin methods and properties here
});
+2  A: 

The easiest (and most reliable) solution I know is to simply use document.write to insert a new script tag into the document (or as many as you need, of course):

<script type="text/javascript">document.write('<' + 'script src="/assets/js/file.js" type="text/javascript"><\/script>');</script>

Browsers will (afaik) parse & execute scripts in the order specified in your document by the script tags, also when added in this way. So you should be good if you put the rest of the code you want to execute in a new, separate, script tag.

EDIT: Here's a (much) more elaborate approach , which in the basis is using "elem = document.createElement('script')", followed by listening to elem.onreadystatechange (for IE) and elem.onload. Will load a whole batch of scripts in parallel, then fire a callback when they're all there. Have used this in the past, when browsers were still mostly loading scripts one at a time to speed up the loading (it's based on a script with similar purposes somewhere out there). Usage example:

Loader.script( [
    './js/jquery/jquery.jmap.js',
    './js/jquery/jquery.getUrlParam.js',
    './js/jquery/jquery.form.js',
    './js/jquery/jquery.gettext.js',
    './js/jquery/jquery.scrollTo.js',
    './js/jquery/jquery.prettydate.js'
  ], { complete: function() {
    // do your thing
  }
})
Paul
document.write is only a viable solution during the initial page load. Using it any time afterwards will over-write the entire page. The problem is a little more complicated than that. http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml explains dynamically loading javascript, but this is not smart enough to realize when it is finished executing the script, even.
steven_desu
Yeah, good one; I've only used this directly in the head, quite a while back.
Paul
The second approach is cross browser compatible?
mellowsoon
Yep, it is. It's a nice modular appraoch as well.
Paul
A: 

A few possible approaches off the top of my head. I'm going to write the steps, not the code.

Option 1

  1. Load the JS file by placing it in the element with a tag.
  2. Right after trigger a setTimout() to check for a variable in the JS file you load.
  3. Repeat #2 until variable is there or until a maxCounter is reached (maxCounter = 10) so that you're not sitting there forever.
  4. Once the variable is there, proceed to the next JS file and start at step 1 again.

Option 2

  1. Use an Ajax approach.
  2. Call the JS file using Ajax.
  3. Append results to the using instructions in the article below.
  4. setTimeout() function to a few seconds and process script OR check for variable similar to option #1 and repeat timeout until variable is present.

reference this article for both approaches: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

The tough part is that you are asking your code to know when each JS file is loaded and processed by the browser. Since computers and browsers vary the time it takes to process a JS file can vary making it difficult to track without some logic in the JS file to do so.

I would prefer an approach like this:

1. Make a Javascript request tag, ajax, whatever to a server that can process dynamic logic (php, java, .NET, etc).

2. Pass a callback function that already exists on the page and knows how many additional JS files you need to know. Even include an index parameter to the callback (something like myCallback(5)) so you know where you are.

1-2a. You could just append the callback function to all your JS files manually and let the function manage the JS queue without the JS files having any knowledge other than the callback function.

3. Let the server append the callback to the JS file being returned.

4. The callback function will be triggered once the JS is processed and it will manage the loading of additional JS files for you.

How about that?

nopuck4you
+1  A: 

Works cross browser, starting with IE6.

document.loadScript = function (src, callback) {
    function script(src, onload) {
        var scriptTag = document.createElement('script');
        if (onload) scriptTag.onload = onload;
        scriptTag.src = src;
        scriptTag.type = 'text/javascript';
        return scriptTag;
    }
    function outer(tag) { 
        var d = document.createElement('div');
        d.appendChild(tag);
        return d.innerHTML;
    }
    if (!(src instanceof Array)) src = [src];
    var i, scr, 
        callbackId = 'dynCall_'+Math.floor(Math.random()*89999+10000);
        counter = src.length, 
        call = function () { if (--counter == 0) callback(); };
    if (!document.body) {
        window[callbackId] = function () {
            delete window[callbackId];
            if (callback instanceof Function) callback();
        };
        for (i=0; i<src.length; i++) document.write(outer(script(src[i])));
        document.write('<scr'+'ipt type="text/javascript">'+'window.'+callbackId+'();'+'</scr'+'ipt>');
        return;
    }
    for (i=0; i<src.length; i++) document.body.appendChild(script(src[i], call));
};

Minified / obfuscated:

(function(){document.loadScript=function(src,callback){function script(src,onload){var scriptTag=document.createElement('script');if(onload)scriptTag.onload=onload;scriptTag.src=src;scriptTag.type='text/javascript';return scriptTag}function outer(tag){var d=document.createElement('div');d.appendChild(tag);return d.innerHTML}if(!(src instanceof Array))src=[src];var i,scr,callbackId='dynCall_'+Math.floor(Math.random()*89999+10000);counter=src.length,call=function(){if(--counter==0)callback()};if(!document.body){window[callbackId]=function(){delete window[callbackId];if(callback instanceof Function)callback()};for(i=0;i<src.length;i++)document.write(outer(script(src[i])));document.write('<scr'+'ipt type="text/javascript">'+'window.'+callbackId+'();'+'</scr'+'ipt>');return}for(i=0;i<src.length;i++)document.body.appendChild(script(src[i],call))};document.loadScript.toString=function(){return'function loadScript() { [obfuscated] }'}})();

Quick explanation of the branches:

If the script tag calling loadScript is within the document head or body, document.body will be undefined, as the DOM isn't in yet. As such, we can't use the standards method of appending a tag, and we must use doc write. This has the advantage that the tags we write will happen in necessarily sequential order, but the disadvantage that we must have a global scope callback function.

Meanwhile, if we have document.body, we're golden for Doing It Right (-ish - we make sacrifices when there's no libraries around to help do it right-er, hence the .onload(). Still, it's not like we're about to throw lots of events on a script tag, so it'll probably be OK.) The disadvantage (maybe?) is that the scripts all load asynchronously, so we need to have a countdown run as they load.

Fordi
Just to be clear... is the scr.onload still going to be called if the browser has the script cached, and isn't actually loading it?
mellowsoon
The scr.onload will be called, cached or not, as long as the onload event is set up *before* the src attribute is. If not, the cache catches before the next JS command goes through. Additional: you may want to pull the script that's up now; I added multiple script support.
Fordi
It appears the outerHTML property isn't supported by Firefox.
mellowsoon
Fixed the outerHTML problem by append-to-div-get-innerHTML
Fordi