Search code examples
javascriptasynchronousloadingpageload

Asynchronous javascript loading gives errors when start using jQuery


I used the manual writen here: http://stevesouders.com/tests/jsorder.php, which gives the folowing scheme lo load JS files asyncroniously:

var sNew = document.createElement("script");
sNew.type = "text/javascript";
sNew.async = true;
sNew.src = "http://yourdomain.com/main.js";
var s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(sNew, s0);

I used this to load additional jQuery plugin files.

So page structure becomes the folowing:

<html><head>

    //meta-tags, css-files loading...
    array of JS files for async load (m)
    code for async load
    some links to js-files (like jquery.js)

    </head><body>

    //page content...

    $(document).ready(function() {
        all jQuery stuff
    )};
</body></html>

probably there's something in structure is wrong, but when opening page in Chrome 15 i get error like Object [object Object] has no method 'XXX', where XXX are functions from those plugins, that were supposed to load asyncroniously.

BTW: in IE9 this problem doesn't seem to appear.


Solution

  • The problem is that your code under document.ready must be executing before the scripts have been loaded. You should use jQuery's getScript inside the $(document).ready:

    $.getScript('plugin-dependency.js', function(){
       //Do Stuff with the loaded plugin
    });
    

    This will make sure your code is running only after the plugin has been loaded.

    More info about jQuery's getScript.