0

Possible Duplicate:
How should I include a js file from another js file?

In one of my js files, I need to use functions from other js file. How would I achieve this?

0

4 Answers 4

1

Just load the dependent file after the source file - e.g. function in file a requires function in file b

<script src="b.js"/> <script src="a.js"/> 

If you want to dynamically load a script file then:

function loadScript(filename){ // find the header section of the document var head=document.getElementsByTagName("head")[0]; // create a new script element in the document // store a reference to it var script=document.createElement('script') // attach the script to the head head.appendChild(script); // set the script type script.setAttribute("type","text/javascript") // set the script source, this will load the script script.setAttribute("src", filename) } loadScript("someScript.js"); 

Google uses this to import the adsense code into a page.

UPDATED

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

1 Comment

I believe that you need to attach your script element to the DOM for the source file to be fetched and loaded, i.e. do something like document.getElementsByTagName("head")[0].appendChild(script);
0

You will need to include both files in any page that uses your functions.

<script type="text/javascript" src="myscript.js"></script> <script type="text/javascript" src="script myscript uses.js"></script> 

The public functions in both files will be available to each other.

You could add a <script> element to the DOM in your script that are pointing to the dependencies - this will allow you to only include your javascript file in a page.

document.write("<script language='javascript' src='script myscript uses.js' />"); 

Comments

0

Including both to the page in the right sequence:

<head> ... <script type="text/javascript" src="library.js"></script> <script type="text/javascript" src="scripts_that_use_library_functions.js"></script> </head> 

Comments

0

You can add js files dynamically in your DOM, like this :

var headID = document.getElementsByTagName("head")[0]; var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = 'http://www.somedomain.com/somescript.js'; headID.appendChild(newScript); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.