Wednesday, September 5, 2018

Importing or Including Other JavaScript Files from Your JavaScript Code

You may have multiple JavaScript files, and you want them all to be included within one page. Normally, that would be several script tags at the head of the document, like so...

<html>
<head>
<script src="MyScript.js"></script>
</head>
<body>
</body>
</html>

But, you may need to determine the name of the JavaScript file you need using JavaScript ocde itself. For instance, you may not be certain that you need MyScript.js, unless the user is logging in through a certain service.

With jQuery, you can include the file very cleanly and with high browser-compatibility. From your JavaScript source library, run this command...

$.getScript("MyScript.js", function() {
console.log("Script loaded!);
});

If you just want to use JavaScript, and nothing else, then you can get away with adding an element of the script type...

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "MyScript.js";
document.appendChild(script);

Then MyScript.js will have been loaded and is then available for use in the local, calling script.

There are a number of other options for handling this: ES6 options, AJAX query options, Node.JS packages, etc., but these are the simplest approaches.

No comments:

Post a Comment