Dynamic script loader with onload callback - markhowellsmead/helpers GitHub Wiki

RequireJS

(A more standardized method for dynamic sequential script loading without jQuery is to use a loader like RequireJS. Jim Hoskins has written a good introduction to how this works.

The following code extends Google Analytics' dynamic loader by adding a callback function, which is executed when the script has loaded.

Load jQuery using vanilla JavaScript

(function(i,s,o,g,r,a,m,x){i['jQueryLoader']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();x=s.createElement(o),
    m=s.getElementsByTagName(o)[0];x.async=1;x.src=g;m.parentNode.insertBefore(x,m);x.onload=a
    })(window,document,'script','https://code.jquery.com/jquery-2.2.4.min.js','jQuery', function(){

    // The script has loaded and you're now in the "onload" callback
    console.log(jQuery);
    console.log($);

});
````

# Load [RequireJS](http://requirejs.org/) from a CDN

This example doesn't need (or conflict with) jQuery.

(function(i,s,o,g,r,a,m,x){i['RequireJsLoader']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();x=s.createElement(o), m=s.getElementsByTagName(o)[0];x.async=1;x.src=g;m.parentNode.insertBefore(x,m);x.onload=a })(window,document,'script','https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js','require', function(){

// The script has loaded and you're now in the "onload" callback console.log(require);

});