How to load CSS and JS files using jQuery

Here is the simple tutorial to load your CSS and JS files using jQuery as we required them. We create 4 files in your web root directory by web design agency.

  • Here is my web root same as yours –> example / www / test.
  • Here I create some files it will help you out – further done by yourself 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>

 

<h2 class=”red”>This blue color is from dynamically loaded css file in script</h2>

 

</body>

</html>

 

  • Now create a file name Main .js

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(“Example.js”);

 

});

 

  • Now create a css file named style.css to add color.

 

Style.css

 

.blue {

color: blue;}

 

Example.js

 

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

 

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

 

});

 

Here we done now you can easily add your js and css in jQuery by follow these steps.