16

Possible Duplicate:
How to include a JavaScript file in another JavaScript file?

I want to include a JavaScript file in a JavaScript file. include('filename.js'); is not working

What is the right code?

Community
  • 1
  • 1
X10nD
  • 21,638
  • 45
  • 111
  • 152

4 Answers4

8
function includeJS(incFile)
{
   document.write('<script type="text/javascript" src="'+ incFile+ '"></script>');
}

Then include a second JavaScript file by calling:

includeJS('filename.js');
Varun Sridharan
  • 1,983
  • 2
  • 20
  • 54
FatherStorm
  • 7,133
  • 1
  • 21
  • 27
6

Use:

<script language="javascript" src="first.js"></script> 
<script language="javascript" src="second.js"></script> 

You can access the variables from the first file in the second file.

There isn't any need to include one JavaScript file into another. JavaScript code is globalised. You can include both the files in the HTML/JSP page.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zod
  • 12,092
  • 24
  • 70
  • 106
  • Unless for some reason, you want th JS to parse what the include file will be... not that likely, but does have application if you want to add some functionality to a page after the initial load... – FatherStorm Oct 21 '10 at 20:18
  • may be .but can you point out a real time situation ?. i saw that cryer.co.uk , but i didnt try. exceptional cases are always there :) – zod Oct 21 '10 at 20:23
  • 1
    Here's a case. I have an ASP page which dynamically determines, based on a database record, if it should load a js file. Which file is also a result of the database record. However, the code is designed to load only 1 js file. If that file has a dependency then I have to load it from javascript. – Sailing Judo Mar 14 '13 at 18:27
2

Use document.write in the first JavaScript function:

document.write('<scr'+'ipt type="text/javascript" src="filename.js" ></scr'+'ipt>'); 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
  • 1
    Why the downvotes? There are caveats, but the upvoted solution employs the same technique. – Pekka Oct 21 '10 at 20:23
  • 1
    @Pekka, thanks for it. I know there are caveats but I think people should leave a comment why they are down voting an answer. After all that's how you learn from your mistakes.. – Teja Kantamneni Oct 21 '10 at 20:26
1

If you do the document.write method bear in mind that the code within the file will not be guaranteed to be loaded once document.write returns.

You may want to have some type of callback mechanism when the included file has loaded. That is, register a callback before document.write, and at the very end of your javascript file make a call to the callback function.

Yasir
  • 11
  • 1