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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With