简体   繁体   中英

How to load resource javascript and css files using javascript / jquery

The project I am working on has lots of javascript and css files. I am using a corportate library that takes care of loading of the resource files by using something like this require("relative file name"). But for some of the pages I dont want to use this library and want to use plain jQuery. I cant use script or style tags to load my javascript (because my content is in iframe and sits in some other pages with a proxy - so all the urls get calculated at run time). I can only use jQuery and Javascript to load these files.

Now I know I could use

$.getScript( <myFileURL>, function( data, textStatus, jqxhr ) {
                  console.log( "Load was performed." );
                  if(jqxhr.status = 200){
                      //call another resource file?
                  }               
            });

The only thing is it seems an overkill to initiate so many async calls to load resource javascript files. The processing can not go ahead unless all the resource files are loaded. Is there any other way of loading all the resource files at once and then only proceed with the page once they are loaded.

EDIT: tried this -

$.when($.getScript( <file1URL>),
               $.getScript( <file2URL>)).then(function(){
                customeFunction();// breakpoint here never gets hits.
          });

When I checked on network tab - I can see the files getting downloaded successfully. But the customFunction() function never gets called. Thanks

$.getScript returns a promise object , so you can do this:

$.when($.getScript( "file1.js"),
       $.getScript( "file2.js"),
       $.getScript( "file3.js")).then(function(){
     //Your code.
});

The requests will be initiated without waiting for the previous one to complete. Once all scripts have been loaded the then handler will be called.

Or if you have an array of filenames:

files = ["one.js", "two.js", "three.js"];
promises = $.map(files, function(file){
    return $.getScript(file.valueOf());
});
$.when.apply($, promises).then(function(){});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM