0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

if i need to load each file unside document.ready then what's for is all that asyncronious stuff?
Your page will load completely, with text and images. And only after that you're gonna call the rest of dependencies, we would consider those staff that are secondary to the page. It's an optimization process.
All the scripts you get using getScript will be asynchronous. The problem with your first code is that some script can be loaded before its dependency.
if i've got a list of JS-files and it can be changing sometimes is a requireJS (requirejs.org) good way out for me?
For sure, requirejs is a way more beautiful solution if you have more then 2 or 3 dependencies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.