-1

I have a bunch of JavaScript links at the bottom of one of my HTML template. I want to create a separate JavaScript file that will only contain all the source links in it.

So instead of cluttering my template footer I want all the links in one JavaScript file. How can I achieve that?

What I'm really asking is how I can get a similar effect as the CSS @import functionality for JavaScript.

And if that is not possible can I place a block of HTML at the footer of my template from a different HTML file?

Bappy
  • 621
  • 1
  • 7
  • 16
  • 3
    http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file – Pang Nov 25 '16 at 04:31

3 Answers3

1

You could do this with ajax but an easy way is to just append them with jquery

$('.div').append('<script src="myscript.js"></script>');

hope that helps

Brad
  • 8,044
  • 10
  • 39
  • 50
0

You can create a seperate js file and a object in it. This object can have multiple keys and their value will these links. Return this object from the file

Hope this snippet will be useful

linkFile.js

var AllLinks = function(){
var _links ={};
_links.keyOne ="link1";
_links.keyTwo ="link2";
return {
 links:_links
 }
}

Also include this file using script tag In other file you can retrieve this value as

AllLinks.links.keyOne & so on

brk
  • 48,835
  • 10
  • 56
  • 78
0

Have an array that holds the link to your script files and then you have two options either to use $.getScript() to load each one Or by building an HTML out of it and appending it to your head or body tag. I prefer head tag to keep all the scripts and css files.

Your array of script files

 var JsFiles = ["script1.js","script2.js","script3.js","script4.js"];

First approach using $.getScript()

JsFiles.each(function(i,v){
  $.getScript(JsFiles[i], function( data, textStatus, jqxhr){
     console.log( textStatus ); // Success
  });
});

Disadvantage of the above approach is that the getScript makes a async calls to your script files that means if the script2.js is dependent on the script1.js (for example if script1.js is some plugin file which use initialize in script2.js) Then you will face issues.

To overcome you might have to then use Promises or write a callback on each getScript success function which will trigger next script load and so on..

If the order of the script loading is not important then above approach is good to go.

Second approach by building HTML

var scriptTags ="";
JsFiles.each(function(i,v){
     scriptTags += "<script src='"+ JsFiles[i] +"'></script>";
});
$('head').append(scriptTags);

Good thing about this approach is that the script files will now load synchronously and you will not face the dependency problem. But make sure the independent files start from first and the dependent files come at last.

Community
  • 1
  • 1
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59