Javascript, Tips and Tricks, Web DevelopmentDynamically 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: Javascript, Tips and Tricks, Web Development

Comments

  1. Be Hai Nguyen

    May 7, 2018 2:55 am

    Thank you. It is a neat solution.
  2. khaled

    May 17, 2017 8:00 am

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

    February 28, 2017 6:50 am

    nice work.............
  4. October 20, 2016 8:58 am

    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
  5. June 3, 2016 5:11 am

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

    September 3, 2015 9:15 am

    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
    1. September 3, 2015 3:44 pm

      @heang do you have a code snippet that i can look at ? - its difficult to say anything without looking at what you are doing
  7. February 18, 2015 10:44 am

    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 !
    1. February 19, 2015 12:14 am

      no you dont need a different variable - you can achieve this in a lot of ways - just use append multiple times and put your file right inside it example: http://jsfiddle.net/naveensnayak/tjcjLf6q/2/
  8. Bernard

    January 12, 2015 8:27 pm

    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...
    1. January 12, 2015 8:42 pm

      @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
      1. Bernard

        January 12, 2015 8:53 pm

        We are running a node server and cache-control was set to false. Changing the value back to "true" resolved the issue I had.
  9. Ravi Prakash Awasthi

    November 3, 2014 10:55 am

    all the files called on main.js loaded initially when loaded my index.html
  10. Ravi Prakash Awasthi

    November 3, 2014 8:40 am

    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............................
  11. July 26, 2014 10:09 pm

    The problem seems to be with this line: When I added "http:" before the //ajax.googleapis.com... etc. then it worked.
  12. July 26, 2014 9:57 pm

    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.
  13. June 17, 2014 12:08 am

    […] I had to set the !important flag here, or would have to set the parent css classes too. I couldn’t find a nice way of loading an external css file into the Editor Page and didn’t really want to modify EditorPage.aspx so we can just load it using jQuery: […]
  14. June 16, 2014 11:17 pm

    […] I had to set the !important flag here, or would have to set the parent css classes too. I couldn’t find a nice way of loading an external css file into the Editor Page and didn’t really want to modify EditorPage.aspx so we can just load it using jQuery: […]
  15. Jigs

    April 22, 2014 10:19 am

    Hello, please help me its not working with google chrome ... :(
    1. April 22, 2014 10:27 pm

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

    March 23, 2014 4:02 pm

    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.
    1. March 23, 2014 4:56 pm

      sry i do not understand you comment - everything is being done after the dom is ready
      1. another scripter

        August 24, 2015 2:56 pm

        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.
        1. August 24, 2015 3:29 pm

          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 ?
  17. haiza

    November 4, 2013 7:21 am

    not working jq1.7.2?
    1. November 4, 2013 1:56 pm

      i have updated the function - it should now work on 1.7
  18. fisherman

    October 10, 2013 2:34 pm

    There is a simple function in jQuery to load a JavaScript file dynamically. Check out http://api.jquery.com/jQuery.getScript/
    1. October 10, 2013 2:53 pm

      this is a good one - updated - thanks !

Post a comment

Your email address will not be published. Required fields are marked *