简体   繁体   中英

Include multiple javascript files in a JS file

So, if I have to include a Javascript file in a .js file, I use to below script. It works fine.

var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {

  //Some code

};
document.getElementsByTagName("head")[0].appendChild(script);

What should I do If I need to include more than 1 files.

You can make a function and pass the js files you want to include like so:

  function scriptLoader(path, callback) { var script = document.createElement('script'); script.type = "text/javascript"; script.async = true; script.src = path; script.onload = function(){ if(typeof(callback) == "function") { callback(); } } try { var scriptOne = document.getElementsByTagName('script')[0]; scriptOne.parentNode.insertBefore(script, scriptOne); } catch(e) { document.getElementsByTagName("head")[0].appendChild(script); } } 

And call it like so:

scriptLoader('/path/to/file.js');

in the similar manner you can call as many JS file you like this:

scriptLoader('/path/to/file2.js');
scriptLoader('/path/to/file3.js');

and even with onload callback functions like so:

scriptLoader('/path/to/file6.js',function(){
    alert('file6 loaded');
});

我想你会做同样的事情,但只需将var script的变量名称更改为var scriptA然后更改var scriptA的代码,以匹配script.src = to scriptA.src =

This function will load one script or many, pass a single file or an array of many:

function include(src, cb) {
  arr = (src instanceof Array) ? src : [{
    'src': src,
    'cb': cb
  }];
  arr.forEach(function(item) {
    _include(item.src, item.cb);
  })

  function _include(src, cb) {
    var script = document.createElement("SCRIPT");
    script.src = src;
    script.async = true;
    script.type = 'text/javascript';
    script.onload = function() {
      if (cb) cb()
    }
    document.getElementsByTagName("head")[0].appendChild(script);
  }
}

include("/js/file1.js");
include("/js/file1.js", function(){console.log("file1 loaded")});
include([{src:"/js/file1.js"},{src:"/js/file2.js"},{src:"/js/file3.js"}]);

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