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 🙂


 <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>
 <h3 class="red">This red color is from dynamically loaded css file</h3>


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

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

 // load the js file 



.red {
    color: red;



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

  1. fisherman
    October 10, 2013 at 2:34 PM

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

    • October 10, 2013 at 2:53 PM

      this is a good one – updated – thanks !

  2. haiza
    November 4, 2013 at 7:21 AM

    not working jq1.7.2?

    • November 4, 2013 at 1:56 PM

      i have updated the function – it should now work on 1.7

  3. Scripter
    March 23, 2014 at 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
    are just “inline” code. To be able to load -really- dynamically scripts, you should call those functions into the
    section. And i’m not sure this will work that way.

    • March 23, 2014 at 4:56 PM

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

      • another scripter
        August 24, 2015 at 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.

      • August 24, 2015 at 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 ?

  4. Jigs
    April 22, 2014 at 10:19 AM

    please help me its not working with google chrome … 😦

    • April 22, 2014 at 10:27 PM

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

  5. July 26, 2014 at 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.

  6. July 26, 2014 at 10:09 PM

    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 3, 2014 at 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……………………….

  8. Ravi Prakash Awasthi
    November 3, 2014 at 10:55 AM

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

  9. Bernard
    January 12, 2015 at 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…

    • January 12, 2015 at 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

      • Bernard
        January 12, 2015 at 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.

  10. February 18, 2015 at 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 :

    var jsLink = $(“,
    } else {
    var jsLink = $(“,

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

    Many thanks !

  11. heang
    September 3, 2015 at 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


    This red color is from dynamically loaded css file

    –> main.js


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

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

    TestJS = function(src) {
    var Link = $(“”);

    // load the css file

    // load the js file


    –> css file

    .red {
    color: red;

    –> one.js


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


    Thanks and best regards for your reply

    • September 3, 2015 at 3:44 PM

      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 3, 2016 at 5:11 AM

    Try OrnaJS, good lib for this task

  13. October 20, 2016 at 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

  14. Ranjith
    February 28, 2017 at 6:50 AM

    nice work………….

  15. khaled
    May 17, 2017 at 8:00 AM

    function loadjscssfile(filename, filetype){
    if (filetype==”js”){ //if filename is a external JavaScript file
    var fileref=document.createElement(‘script’)
    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”)

    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 16, 2014 at 11:17 PM
  2. June 17, 2014 at 12:08 AM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: