tags:

views:

108

answers:

5

Possible Duplicate:
Include javascript file inside javascript file?

Hello,

I want to include a javascript file in a javascript file.

include('filename.js'); is not working

What is the right code.

Thanks Jean

+2  A: 
    function includeJS(incFile)
{
  document.write('<script type="text/javascript" src="'
    + incFile+ '"></scr' + 'ipt>'); 
}
</script>

Then include a second JavaScript file by calling:

includeJS('filename.js');
FatherStorm
note that the call will return before the javascript file is loaded
Frank Schwieterman
This code will be placed in a js file not html or php, will it work out?
Jean
yes. it is specifically javascript in implementation
FatherStorm
Now with <a href="http://www.cryer.co.uk/resources/javascript/script17_include_js_from_js.htm">attribution</a>: A. B. Cryer.
Eric Towers
Don't use string concatenation to avoid `</script>` ending an inline script, `<\/script>` is much more readable (and marginally faster).
David Dorward
I think you officially are not allowed to use `document.write` after the page has been parsed though.
Bart van Heukelom
A: 

use document.write in first javscript function..

document.write('<scr'+'ipt type="text/javascript" src="filename.js" ></scr'+'ipt>'); 
Teja Kantamneni
Why the downvotes? There are caveats, but the upvoted solution employs the same technique.
Pekka
@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
+5  A: 
<script language="javascript" src="first.js"></script> 
<script language="javascript" src="second.js"></script> 

You can access the variables from first in second

There is no need to include one js file into another. Javascripts are globalised one. You can include both the files in the HTML/JSP page.

zod
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
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
A: 

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