Wednesday, 21 January 2015

Filled Under:

Include a JavaScript file in another JavaScript file?

Ever wondered including a JavaScript file inside another JavaScript, it is basically like embedding or invoking other file from inside a file, just like @import in CSS. Well there is no @import like mehtod but it could be achieved.

jQuery Loading

jQuery provides a loading functionality using getScript method. We can load JS files using this method except we could not use it to load jQuery itself.
$.getScript("myScript.js", function(){
alert("Script loaded and executed."); // Use anything defined in the loaded script...
});

Dynamic Script Loading with JavaScript


function loadScript(url, callback)
{
// Adding the script tag to the head
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
script.onreadystatechange = callback;
script.onload = callback;
// There are several events for cross browser compatibility.

// Fire the loading
head.appendChild(script);
}
Then you write the code you want to use AFTER the script is loaded:
var myCoding = function() {
// Here, do what ever you want
};
Then you run all that:
loadScript("mainScript.js", myCoding);

Ajax Loading

Load an additional script with an Ajax call and then use eval. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also makes you code vulnerable.

0 comments:

Post a Comment