user1870829
user1870829

Reputation:

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?

Upvotes: 1

Views: 191

Answers (5)

s1lence
s1lence

Reputation: 2188

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).

Upvotes: 1

geocar
geocar

Reputation: 9305

  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.

Upvotes: 2

Brad
Brad

Reputation: 163292

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.

Upvotes: 0

LPD
LPD

Reputation: 2883

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.

Upvotes: 0

antyrat
antyrat

Reputation: 27765

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

Upvotes: 1

Related Questions