loading js files and other dependent js files asynchronously
Asked Answered
P

5

14

I'm looking for a clean way to asynchronously load the following types of javascript files: a "core" js file (hmm, let's just call it, oh i don't know, "jquery!" haha), x number of js files that are dependent on the "core" js file being loaded, and y number of other unrelated js files. I have a couple ideas of how to go about it, but not sure what the best way is. I'd like to avoid loading scripts in the document body.

So for example, I want the following 4 javascript files to load asynchronously, appropriately named:


/js/my-contact-page-js-functions.js // unrelated/independent script
/js/jquery-1.3.2.min.js // the "core" script
/js/jquery.color.min.js // dependent on jquery being loaded
http://thirdparty.com/js/third-party-tracking-script.js // another unrelated/independent script

But this won't work because it's not guaranteed that jQuery is loaded before the color plugin...


(function() {
    var a=[
      '/js/my-contact-page-functions.js',
      '/js/jquery-1.4.2.min.js',
      '/js/jquery.color.js',
      'http://cdn.thirdparty.com/third-party-tracking-script.js',
    ],
    d=document,
    h=d.getElementsByTagName('head')[0],
    s,
    i,
    l=a.length;
    for(i=0;i<l;i++){
        s=d.createElement('script');
        s.type='text/javascript';
        s.async=true;
        s.src=a[i];
        h.appendChild(s);
    }
})();

Is it pretty much not possible to load jquery and the color plugin asynchronously? (Since the color plugin requires that jQuery is loaded first.)

The first method I was considering is to just combine the color plugin script with jQuery source into one file.

Then another idea I had was loading the color plugin like so:


$(window).ready(function() {
    $.getScript("/js/jquery.color.js");
});

Anyone have any thoughts on how you'd go about this? Thanks!

Purify answered 5/5, 2010 at 21:47 Comment(0)
T
4

LabJS and RequireJS are two popular choices right now. They both work with jQuery but take slightly different approaches, so you should look at both.

Tumefy answered 8/5, 2010 at 15:3 Comment(3)
LAB seems to no longer be maintained, so I changed the accepted answer to yours, since you mentioned RequireJS. (Probably a better choice nowadays!) Hopefully this is the "right" thing to do for older questions here on SO.Purify
is there a new es6+ way to do this with async and defer?Fieldwork
There are several modern ways to do this, and async and defer are two good tools to be aware of. It seems like the tools like webpack and requirejs call this feature "on-demand chunk loading", so you can look for that.Tumefy
P
11

LABjs is made specifically for this problem.

<script src="lab.js"></script>
<script>
  $LAB
    .script("jquery.js")
    .wait()
    .script("jquery.color.js")
    .script("jquery.otherplugin.js")
    .script("mylib.js")
    .wait()
    .script("unrelated1.js")
    .script("unrelated2.js");
</script>

You could also put the unrelated scripts into their own $LAB chain, if they really have no need to wait for jQuery and your other scripts.

Polymer answered 5/5, 2010 at 22:56 Comment(5)
thanks, if i wanted to load lab.js asynchronously too, how would i know when $LAB exists and is ready to be called? would i need to use something like: function initLab(){ ... } ... document.onload = initLab;Purify
You could do something like that, but I'd advise against it. LAB.js is only 4.5k after minification (only 2.1k across the wire gzipped). If you wanted, you could inline the LABjs code into a <script> tag in the HTML document, but loading as a synchronous <script src> should be fine at its size.Polymer
ah-ha, and i can pass .wait() an anonymous function to postpone init routines etc. until the previous js files have loaded. awesome, thanks.Purify
@Purify Mining an old thread, the site's been updated to include Snippet to load LABjs itself dynamically gist.github.com/603980Emphasize
this method need to use <script> tag to link a js file, not inline script, also require a load script pluginTechnics
T
4

LabJS and RequireJS are two popular choices right now. They both work with jQuery but take slightly different approaches, so you should look at both.

Tumefy answered 8/5, 2010 at 15:3 Comment(3)
LAB seems to no longer be maintained, so I changed the accepted answer to yours, since you mentioned RequireJS. (Probably a better choice nowadays!) Hopefully this is the "right" thing to do for older questions here on SO.Purify
is there a new es6+ way to do this with async and defer?Fieldwork
There are several modern ways to do this, and async and defer are two good tools to be aware of. It seems like the tools like webpack and requirejs call this feature "on-demand chunk loading", so you can look for that.Tumefy
A
1

You can leverage the YUI Loader to register your own modules and dependencies and then load them.

You get complete hooks for success, failure, and even progress, so you can hook any asynchronous action you like.

Amann answered 5/5, 2010 at 22:3 Comment(0)
I
0

You won't be able to achieve a completely async load for the very reason you mention; dependency.

For my 10p, I'd follow the $.getScript() route. It's basically just a wrapper for $.ajax(), so loading your scripts in this way will give you the asynchronous loading you're after.

Institution answered 5/5, 2010 at 22:4 Comment(0)
C
0

There is a general jquery plugin that loads css and JS files asynch and synch see: http://code.google.com/p/rloader/

Clapperclaw answered 12/12, 2010 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.