Dynamically add a JS or CSS file with jQuery or JavaScript

JavaScript, CSS or other library file is required to add by the programmer to load dynamically or say programmatically. Usually based on if a condition is satisfied. The simplest way is through jQuery but also possible with pure JavaScript.

Following way programmer may include a JavaScript file in another JavaScript file.

jQuery to add file dynamically

jQuery may add the file both ways, synchronously as well as asynchronously

synchronously

Synchronous program code:

$.getScript('/javascript/myscript.js');

//use following if you want to code after load
$.getScript('/javascript/myscript.js', function() {
    // optional code when success on loading
});

asynchronously

Asynchronous program code:

$.ajax({
    url: '/javascript/myscript.js',
    dataType: 'script',
    success: function(){
		// optional code when success on loading
		}
});

JavaScript to add file dynamically

Using pure JavaScript to add file without dependency of other library:

//for script
var el=document.createElement("script");
el.setAttribute("type","text/javascript");
el.setAttribute("src", "filename.js");

//for css
var el=document.createElement("link");
el.setAttribute("rel", "stylesheet");
el.setAttribute("type", "text/css");
el.setAttribute("href", "fielname.css");

(document.getElementsByTagName("head")[0]||document.body).appendChild(el);
Posted Status in Programming
Login InOR Register