13

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

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

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

Have you any tips about that?

Rodrigue
  • 3,617
  • 2
  • 37
  • 49
mati
  • 5,218
  • 3
  • 32
  • 49

2 Answers2

11

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
  • 132,184
  • 23
  • 144
  • 116
  • what about dealing with already loaded scripts ? Is there a simple pattern for `if(!Isloaded("otherscript.js")) { document.write(myscriptdeclaration);} ` ? – Steve B May 17 '12 at 11:06
4
document.write( '<script language="javascript" src="myotherscript.js" />' );
Paul Alexander
  • 31,970
  • 14
  • 96
  • 151