Saturday, 27 June 2015

Dynamically load css and javascript

We can load css and javascript files dynamically using jquery/Javascript

Load javascript files using jquery


  var j = document.createElement('script');
  j.type = 'text/javascript';
  j.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(j);

Load Jquery if it is not loaded


 if ( typeof( jQuery ) == 'undefined' ){
  var j = document.createElement('script');
  j.type = 'text/javascript';
  j.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(j);
 }

Load CSS using jquery


 var ls = document.createElement('link'),
 ls.rel="stylesheet';
 ls.href= 'youcss.css";
 document.getElementsByTagName('head')[0].appendChild(ls);

Load css if not loaded already


 var links = document.getElementsByTagName('link'),
 needCSS = true;
 for ( var i = 0; i < links.length; i++ )
 {
  if ( links[i].href == "yourcss.css" ) 
  needCSS = false;
 }
 if ( needCSS )
 {
  var ls = document.createElement('link');
  ls.rel="stylesheet";
  ls.href="yourcss.css";
  document.getElementsByTagName('head')[0].appendChild(ls);
}

Related Posts

1. Covert string to camel case using javascript.

2. How to remove duplicate from an array and get count of duplicated .

3. Angular js add class to active element


1 comment :

  1. This might be a bit old topic but Just created a new components uses ES6 to load scripts dynamically in synchronous way. The Project details and source code are on GitHub https://github.com/amgadfahmi/scripty


    ReplyDelete