Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I include a js file from another js file?

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?

like image 953
mati Avatar asked May 09 '09 02:05

mati


People also ask

Can I use a JavaScript function from another file?

As long as both are referenced by the web page, yes. You simply call the functions as if they are in the same JS file.


2 Answers

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.

like image 55
Ayman Hourieh Avatar answered Nov 15 '22 16:11

Ayman Hourieh


document.write( '<script language="javascript" src="myotherscript.js" />' );
like image 35
Paul Alexander Avatar answered Nov 15 '22 15:11

Paul Alexander