Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using external javascript files in a .js file

Tags:

javascript

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

like image 954
David Menard Avatar asked Apr 05 '10 17:04

David Menard


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.

How do you call another JS file in JS?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.

When would it be a good idea to use an external JavaScript file?

To enhance performance, try to keep JavaScript external. The separate code makes it easier for web browsers to cache. However, use inline scripts only when you're making single page websites. Still, it's better to use external code i.e. external JavaScript.

Should JavaScript be in external file?

Placing scripts in external files has some advantages: It separates HTML and code. It makes HTML and JavaScript easier to read and maintain. Cached JavaScript files can speed up page loads.


2 Answers

Javascript doesn't have any implicit "include this other file" mechanisms, like css's @include. You just have to list your globals file before the logic file in the tags:

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

If guaranteeing that the globals are available before anything in the logic file fires up, you can do a slow polling loop to see if some particular variable is available before calling an init() or whatever function.

like image 164
Marc B Avatar answered Sep 30 '22 19:09

Marc B


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

Edit: Actually, this probably won't work for your purposes, as global.js variables won't be accessible until logic.js completes. You may be able to wrap logic.js in a function that is called after global.js loads. Otherwise I don't think there is a way to do what you're asking.

like image 29
tloflin Avatar answered Sep 30 '22 19:09

tloflin