Follow @endyourif rss Facebook LinkedIn

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

Published on Jan 28, 2020

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.



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 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...

Tags: Javascript | JavaScript | import

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP