LEE
LEE

Reputation: 3605

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.

Upvotes: 1

Views: 11206

Answers (3)

MartinWebb
MartinWebb

Reputation: 2008

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"}]);

Upvotes: 0

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

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');
});

Upvotes: 6

Mas0490
Mas0490

Reputation: 86

I would imagine you'd do the same as you've got there but just change the variable name from var script to something like var scriptA and change the code that follows to match like script.src = to scriptA.src =

Upvotes: 0

Related Questions