js.id=id; -- apply id to newly created script tag :: js.src=jsfilename; - apply file name in src so it load JavaScript when it embed to HTML DOM :: fjs.parentNode.insertBefore(js,fjs); - insert script tag :: before all script tag. as script tag embed to HTML DOM , it load JavaScript from path of src of script tag. ", "dateCreated": "0000-00-00 00:00:00", "upvoteCount": 2, "url": "https://www.arrayoverflow.com/question/how-to-include-a-javascript-file-in-another-javascript-file/241#250", "author": { "@type": "Person", "name": "Phpworker" } } ] } }
Asked 7 years ago
7 Jan 2017
Views 1110
Rasi

Rasi posted

how to include a JavaScript file in another JavaScript file?

how one can include one JavaScript file to another JavaScript file ?
as like css have @import to include another css . do we have same import function or something to include JavaScript file to another JavaScript file

import one.js
.. .  ..
//other code here


or php have include and require function to include in one PHP file to another PHP file ,
so we have include function in JavaScript to include another file in one.

//js file 
include("one.js");
.. .  ..
//other code here


Phpworker

Phpworker
answered Nov 30 '-1 00:00

insert JavaScript in to dom also same as insert one JavaScript file in to another JavaScript file.

i made function for imports files in to HTML DOM before script tag.

					
function imports(jsfilename,id){

	var js,fjs=document.getElementsByTagName('script')[0];
	if(!document.getElementById(id)){
		js=document.createElement('script');
		js.id=id;
		js.src=jsfilename;
		fjs.parentNode.insertBefore(js,fjs);
	}
}

it simpliefied version of twitter script which used to load "platform.twitter.com/widgets.js" into HTML

so call like this to imprt JavaScript into HTML DOM

imports("//platform.twitter.com/widgets.js","twitter-wjs");


Syntax : imports(filename,id)
filename is file name with full path to include
and id is id of script tag which hold script which is included . for future reference .

LET ME EXPLAIN CODE
fjs=document.getElementsByTagName('script')[0]; ask for first script tag from HTML DOM
Now
js=document.createElement('script'); -- create an element named "script" ::<script></script>
js.id=id; -- apply id to newly created script tag :: <script id='twitter-wjs'></script>
js.src=jsfilename; - apply file name in src so it load JavaScript when it embed to HTML DOM :: <script id='twitter-wjs' src="//platform.twitter.com/widgets.js"></script>

fjs.parentNode.insertBefore(js,fjs); - insert script tag :: <script id='twitter-wjs' src="//platform.twitter.com/widgets.js"></script> before all script tag.

as script tag embed to HTML DOM , it load JavaScript from path of src of script tag.
Post Answer