简体   繁体   中英

JavaScript includes

I have 4 javascript files (each for a single HTML file) and 3 functions are THE SAME in all 4 files. I'd like to find a smooth solution that I could somehow include these 3 functions separately... is it possible to include .js within a .js?

  1. You can have multiple <script> tags:

     <script src="lib.js"></script> <script> // do stuff </script> 
  2. You can use jQuery :

     $.getScript("lib.js", function() { // do stuff }); 
  3. You can use a pre-processor like browserify or YUICompressor or Google's Closure Compiler .

You can write this by your own, for example as it works in google analytics:

(function(){
    var lastIncludedScript = document.getElementsByTagName('script')[0];
    var yourScript = document.createElement('script');
    yourScript.type = 'text/javascript';
    yourScript.src = 'path/to/script.js';
    lastIncludedScript.parentNode.insertBefore(yourScript, lastIncludedScript);
})();

or as in function:

function includeScript( path ){
    var lastIncludedScript = document.getElementsByTagName('script')[0];
    var yourScript = document.createElement('script');
    yourScript.type = 'text/javascript';
    yourScript.src = path;
    lastIncludedScript.parentNode.insertBefore(yourScript, lastIncludedScript);
}

usage:

includeScript( 'path/to/script.js' );

You can have a look at this nice explanation about loading javascript files asynchronously. This could solve your problem. Or look at this stack overflow question on how to load javascript files inside other javascript files.

However it may be worth a shot to include everything you use in one single javascript file and load the same one on every site. This improves performance because only one http request has to be made to load all javascript and it can be cached very efficiently (so no need to load any javascript later on).

Use proper js file required in each html file. That will solve your issue. Also the one contating the general functions can be added for both html files. This should solve your problem.

It's a bit slow to include files from other JavaScript in the browser. I would write a server-side script to combine and minify all relevant JavaScript into one "file" to be sent to the client.

Your pages can pass parameters to this script to choose what needs to be included.

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