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?

Community
  • 1
  • 1
codematrix
  • 1,571
  • 11
  • 35
  • 53

4 Answers4

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

web_bod
  • 5,728
  • 1
  • 17
  • 25
  • 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);` – Rodrigue May 19 '12 at 17:25
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' />");
Oded
  • 489,969
  • 99
  • 883
  • 1,009
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>
VisioN
  • 143,310
  • 32
  • 282
  • 281
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);  
Geraud Mathe
  • 711
  • 2
  • 9
  • 20