Home > Jquery, Tips and Tricks, Web Development > Dynamically loading CSS and JS files using jQuery

Dynamically loading CSS and JS files using jQuery

Simple tutorial on how we can use jquery to load CSS and JS files as and when we require them

We will create 4 files ( in the same directory of your web root – mine is /var/www/test )

  • index.html : the main html file
  • main.js : the main JS file which will be included in main.html along with the jquery library
  • style.css : this file will be dynamically loaded using main.js
  • one.js : this file will be dynamically loaded using main.js

the files are here – rest of this is self explanatory 🙂

index.html

<html>
 <head>
 <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script type="text/javascript" src="main.js"></script>
 </head>
 <body>
 <h3 class="red">This red color is from dynamically loaded css file</h3>
 </body>
</html>

main.js

jQuery(document).ready(function($){
 
 /**
  * function to load a given css file 
  */ 
 loadCSS = function(href) {
     var cssLink = $("<link rel='stylesheet' type='text/css' href='"+href+"'>");
     $("head").append(cssLink); 
 };

/**
 * function to load a given js file 
 */ 
 loadJS = function(src) {
     var jsLink = $("<script type='text/javascript' src='"+src+"'>");
     $("head").append(jsLink); 
 }; 
  
 // load the css file 
 loadCSS("style.css");

 // load the js file 
 loadJS("one.js");

});

style.css

.red {
    color: red;
}

one.js

jQuery(document).ready(function($){

    alert("This alert is from dynamically loaded js file");

});
Categories: Jquery, Tips and Tricks, Web Development Tags:
  1. fisherman
    October 10th, 2013 at 14:34 | #1

    There is a simple function in jQuery to load a JavaScript file dynamically. Check out http://api.jquery.com/jQuery.getScript/

  2. haiza
    November 4th, 2013 at 07:21 | #3

    not working jq1.7.2?

  3. Scripter
    March 23rd, 2014 at 16:02 | #5

    This scripts don’t load the files “dynamically”..they just load them before the dom is ready. In fact, the function calls
    loadCSS(“style.css”);
    loadJS(“one.js”);
    are just “inline” code. To be able to load -really- dynamically scripts, you should call those functions into the
    jQuery(document).ready(function($){});
    section. And i’m not sure this will work that way.

    • March 23rd, 2014 at 16:56 | #6

      sry i do not understand you comment – everything is being done after the dom is ready

      • another scripter
        August 24th, 2015 at 14:56 | #7

        no, i don’t really understand the comment, either – except that you’re not really loading the files “dynamically”, as you claim. you’re just loading them after the document ready state completes, and you’re not checking when those file loads complete. which isn’t a problem as far as the css styles are concerned; they’ll just be applied when each inserted link element finishes loading. but it might be a problem for jscript files, especially if you’re using your load schema in, say, a bookmarklet to fetch a javascript framework that your bookmarklet subsequently uses. if your fetched jscript is just a piece of self-contained code, your schema will work. otherwise something like the techniques demonstrated @ https://gist.github.com/lpsBetty/5636338 might be more appropriate.

        • August 24th, 2015 at 15:29 | #8

          can you suggest a better title if you are getting confused – will “on demand loading” make things a bit clear ?
          what i mean by dynamic is that the javascript is being attached to the page after the document loads from the server
          the javascript is not included as part of the initial page load or page html

          lets say you have a page loaded and then you want to create a new div – what would you call that process of adding a new div ?

  4. Jigs
    April 22nd, 2014 at 10:19 | #9

    Hello,
    please help me its not working with google chrome … 🙁

    • April 22nd, 2014 at 22:27 | #10

      @Jigs,
      what is not working?
      are there any javascript errors ?
      do you have an example – can you put your code into pastebin ?

  5. July 26th, 2014 at 21:57 | #11

    Doesn’t work in Firefox or Chrome. I copied the four files verbatim into a folder, then brought up index.html in my browser. The text in the body is black, not red, and the alert from one.js never appears.

  6. July 26th, 2014 at 22:09 | #12

    The problem seems to be with this line:

    When I added “http:” before the //ajax.googleapis.com… etc. then it worked.

  7. Ravi Prakash Awasthi
    November 3rd, 2014 at 08:40 | #13

    it works but when we set a path for a root directory either for a css file or for js file it doesn’t works……………………….

  8. Ravi Prakash Awasthi
    November 3rd, 2014 at 10:55 | #14

    all the files called on main.js loaded initially when loaded my index.html

  9. Bernard
    January 12th, 2015 at 20:27 | #15

    Hi, thank you for this! It works wonderfully for the CSS files.

    However, when using a source such as : “/libs/highcharts.js”, the following error displays in the console :
    GET http://myDomain.com/libs/highcharts.js?_=1421092721637 404 (Not Found)

    Any idea why it’s concatenating “?_=1421092721637” at the end of the name of the file? Knowing that “http://myDomain.com/libs/highcharts.js” is a valid path/filename, I can’t make any sense as to why I am getting this error…

    • January 12th, 2015 at 20:42 | #16

      @Bernard – looks like something is appending a timestamp to the javascript files your are requesting

      Are you using any kind of framework ?
      This is typically used for caching – if you modify the js file, a new timestamp will be appended and the browser will download the new changed JS file

      The script in this post does not modify anything, it just includes the exact URL that was given – check on your server side where this timestamp is being appended

      • Bernard
        January 12th, 2015 at 20:53 | #17

        We are running a node server and cache-control was set to false. Changing the value back to “true” resolved the issue I had.

  10. February 18th, 2015 at 10:44 | #18

    Hello i was wondering if it’s possible to load on the same variable multiple js files and then append all of those to the head, something like this :

    if(!$(‘html’).is(‘ie8’)){
    var jsLink = $(“,
    ,
    ,
    ,
    “);
    $(“head”).append(jsLink);
    } else {
    var jsLink = $(“,
    ,
    “);
    $(“head”).append(jsLink);
    }

    Do i have to use a different variable for each .js file i want to load ?

    Many thanks !

  11. heang
    September 3rd, 2015 at 09:15 | #20

    hello scripter

    Thanks for your code. i would like ask you some question when I follow your code it work only css file but for js file it not work.
    Why did it not work?Could you help me?

    –> html code

    http://jquery-1.11.2.min.js
    http://main.js

    This red color is from dynamically loaded css file

    –> main.js

    jQuery(document).ready(function($){

    /**
    * function to load a given css file
    */
    loadCSS = function(href) {
    var cssLink = $(“”);
    $(“head”).append(cssLink);
    };

    /**
    * function to load a given js file
    */
    loadJS = function(src) {
    var jsLink = $(“”);
    $(“head”).append(jsLink);
    };

    TestJS = function(src) {
    var Link = $(“”);
    $(“head”).append(jsLink);
    };

    // load the css file
    loadCSS(“style.css”);

    // load the js file
    loadJS(“one.js”);

    });

    –> css file

    .red {
    color: red;
    }

    –> one.js

    jQuery(document).ready(function($){

    alert(“This alert is from dynamically loaded js file”);

    });

    Thanks and best regards for your reply

    • September 3rd, 2015 at 15:44 | #21

      @heang
      do you have a code snippet that i can look at ? – its difficult to say anything without looking at what you are doing

  12. June 3rd, 2016 at 05:11 | #22

    Try OrnaJS, good lib for this task
    ornaorg.github.io

  13. October 20th, 2016 at 08:58 | #23

    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

  14. Ranjith
    February 28th, 2017 at 06:50 | #24

    nice work………….

  15. khaled
    May 17th, 2017 at 08:00 | #25

    function loadjscssfile(filename, filetype){
    if (filetype==”js”){ //if filename is a external JavaScript file
    var fileref=document.createElement(‘script’)
    fileref.setAttribute(“type”,”text/javascript”)
    fileref.setAttribute(“src”, filename)
    }
    else if (filetype==”css”){ //if filename is an external CSS file
    var fileref=document.createElement(“link”)
    fileref.setAttribute(“rel”, “stylesheet”)
    fileref.setAttribute(“type”, “text/css”)
    fileref.setAttribute(“href”, filename)
    }
    if (typeof fileref!=”undefined”)
    document.getElementsByTagName(“head”)[0].appendChild(fileref)
    }

    loadjscssfile(“myscript.js”, “js”) //dynamically load and add this .js file
    loadjscssfile(“javascript.php”, “js”) //dynamically load “javascript.php” as a JavaScript file
    loadjscssfile(“mystyle.css”, “css”) ////dynamically load and add this .css file

  1. June 16th, 2014 at 23:17 | #1
  2. June 17th, 2014 at 00:08 | #2