Include a JavaScript file in another file Include a JavaScript file in another file

Including a JavaScript file into another file is a very nice thing to be able to do. It's something you probably do with almost every other language; it helps keeping files smaller, more readable, and of course, more readable. There are multiple ways to accomplish this and I'll let you pick the one that works best for you without using the Javascript string replace() function.


Loading a JavaScript file with jQuery

jQuery provides a one-line example to import a file into another JavaScript file:


$.getScript('file1.js');

Because this requires downloading the file by the user's browser, it is not instantaneous. Similar to an ajax request, jQuery provides a callback function so you know when it is done:


$.getScript('file1.js', function() {
// Functions and variables are now ready for use
});

Dynamic JavaScript file loading

By using the DOM (Document Object Model) you can access the HTML with JavaScript event handler and inject the file into the head tag:


function loadFile(url) {
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
};
loadFile('file1.js');

If you prefer to put it in the body instead of the head tag, replace head with body in the example above.

AJAX loading a JavaScript file

This is my least favorite way, but ironically the first way I learned when I first started. It requires use of the eval function which can be limited by browsers because of the security of executing dynamic JavaScript code:


$.ajax(
url: 'file1.js',
done: function(data) {
eval(data);
}
);

It's not pretty, but can do the job if need be...

Published on Jan 28, 2020

Tags: Javascript | JavaScript | import

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.