Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include js file in another js file? [duplicate]

Tags:

javascript

How can I include a js file into another js file , so as to stick to the DRY principle and avoid duplication of code.

like image 839
Aditya Shukla Avatar asked Jan 08 '11 15:01

Aditya Shukla


People also ask

How do I transfer data from one JavaScript to another?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.


1 Answers

You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:

var imported = document.createElement('script'); imported.src = '/path/to/imported/script'; document.head.appendChild(imported); 

There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.

// jQuery $.getScript('/path/to/imported/script.js', function() {     // script is now loaded and executed.     // put your dependent JS here. }); 
like image 118
Matt Ball Avatar answered Oct 28 '22 13:10

Matt Ball