Include a JavaScript file in another file

I

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:

[code]
$.getScript(‘file1.js’);
[/code]

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:

[code]
$.getScript(‘file1.js’, function() {
// Functions and variables are now ready for use
});
[/code]

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:

[code]
function loadFile(url) {
var script = document.createElement(“script”);
script.src = url;

document.head.appendChild(script);
};

loadFile(‘file1.js’);
[/code]

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:

[code]
$.ajax(
url: ‘file1.js’,
done: function(data) {
eval(data);
}
);
[/code]

It’s not pretty, but can do the job if need be…

About the author

By Jamie

My Books