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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

what about dealing with already loaded scripts ? Is there a simple pattern for if(!Isloaded("otherscript.js")) { document.write(myscriptdeclaration);} ?
4
document.write( '<script language="javascript" src="myotherscript.js" />' ); 

3 Comments

In my opinion, "document.write" is very inelegant.
Why? It's universally accepted and easy to use. There's no language equivalent.
document.write is bad because it prevents async loading of your JS.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.