views:

728

answers:

2

What is the better way to add a reference to a javascript file from another javascript file?

Supose that I have one js file included in my webpage. This javascript has a dependency to another file. So I want to reference the dependency within the original js file, and not from the html code. Is my thought correct?

I know I can create an 'script' DOM element and then append it to the page, but that smells bad for me.

Have you any tips about that?

+9  A: 

Creating a script DOM element is the only available way as far as I know. After checking the source code of jQuery and YUI, I couldn't find a better way. Both use this technique. Check out the globalEval function in jQuery, and the _scriptNode function in YUI.

Ayman Hourieh
+2  A: 
document.write( '<script language="javascript" src="myotherscript.js" />' );
Paul Alexander
In my opinion, "document.write" is very inelegant.
Steve Harrison
Why? It's universally accepted and easy to use. There's no language equivalent.
Paul Alexander