Steven
Steven

Reputation: 19425

How can I dyamically load multiple scripts by order?

I'm lazy loading various scripts depending on what page I'm on. Up till now, I've only loaded one per page. Now that I'm starting to clean up and reduce the number of scripts, I have to lazy load two scripts (or more) scripts for the same page. One script is dependent of the other so I need to load these in correct order.

What is the best way to achieve this?

My code:

// Plupload must load before imageHandling.js
jQuery(document).ready(function() {
    //Conditional load
    load_script('.image-drop-box','vendor/plupload/plupload.full.min.js');
    load_script('.image-drop-box','imageHandling.js');

});


// Script loader
// .exists() is a custom func that checks if an element exists on page
function load_script(element, js) {
    $(element).exists(function(){
        var script = document.createElement('script');
        var footer = document.getElementById('footer');
        script.type = 'text/javascript';
        script.src = '/js/'+ js;
        footer.appendChild(script);
    });
}

Upvotes: 2

Views: 1475

Answers (3)

shaN
shaN

Reputation: 828

there is a jquery plugin with callback. you could use that, the call back function will be triggered after loading the first script, this plugin uses lazyloading system

jquery loadscript plugin usage

$.loadScript( url [, callback()] )


or

var s= ["http://firstLink", "http://secondLink"];
function get_script(){
    if(scripts.length==0)
        return;
    var x = s.pop();
    $.ajax({
      url: x,
      dataType: "script",
      async:true,
      success: function(){
        get_script();
      },
      error: function(){
            //console.log( x+ 'failed' );
      }
    });
}
get_script();

even though second one looks lengthy, i prefer that.(just a personal opinion, correct me if there is a better option)

Upvotes: 3

spender
spender

Reputation: 120400

If you're not stepping out of the same domain, you could use getScript()

var scriptUrls = ["http://x/foo", "http://x/bar"];
var loadScr;
loadScr = function(){
    if(scriptUrls.length==0)return;
    var currentUrl = scriptUrls.pop();
    $.getScript(url, loadScr);
}
loadScr();

Upvotes: 1

user4342201
user4342201

Reputation: 1

Do you mean to ensure that the scripts are loaded in correct order even if they are writted in wrong order? Maybe you should give your function the objects as array and check it in a "while" loop to ensure that no one is loaded until his "previous requeriments" have been loaded. But you need or write and read this requeriments from .js or make a list with requeriments.

Upvotes: 0

Related Questions