Using external javascript files in a .js file

I would like to use an external javascript file in another javascript file. For example, I could store all my global variables in the globals.js file, and then call them from the logic logic logic.js. Then in index.html I insert the tag. How to use globals.js inside logic.js?

+7
javascript
source share
5 answers

Javascript does not have any implied "include this other file" mechanisms, such as css @include. You just need to list your globals file before the logical file in tags:

<script type="text/javascript" src="globals.js" /> <script type="text/javascript" src="logic.js" /> 

If you guarantee that globals are available before anything in the logical file works, you can do a slow polling cycle to find out if any particular variable is available before calling the init () function or any other function.

+9
source share
 document.write('<script type="text/javascript" src="globals.js"></script>'); 

Edit: Actually, this probably won't work for your purposes, since the global.js variables will not be available until logic.js completes. You might be able to port the logic.js function to the function called after loading global.js. Otherwise, I donโ€™t think there is a way to do what you ask.

+5
source share
 function loadExternalJS(TARGET_URL){ var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); xhr.open('GET', TARGET_URL, false); xhr.send(null); var code = xhr.responseText; var dScript = document.createElement('script'); try { dScript.appendChild( document.createTextNode(parsed) ); document.body.appendChild(dScript); } catch(e) { dScript.text = parsed; document.getElementsByTagName('head')[0].appendChild(dScript); } xhr = null; 
+5
source share

Just make sure both files are listed in your index.html.

+2
source share

You can also do something like this:

 $(document).ready(function(){ $('body').append($('<script src="/path/to/script/foo.min.js"></script>')); }); 

Just use this line before you need to reference something in the included js file.

0
source share

All Articles