SHARE

Load CSS Dynamically In Webpage Using Javascript

With load CSS stylesheet dynamically ,webpage loading speed is boost .It make a positive impact on SEO . With load it using a script you can place your css at bottom of the webpage without interrupt the user experience .

In this article i tell you two methods to load css using javascript or jquery . In first method css is load using jquery and in second method style sheet is load using javascript .

Method 1 Using JQuery

In this method CSS load using JQuery . In this style.css is url .Change this url with your custom url ‘ http://example/css/bootstrap.min.css’.

Example Code

<script type="text/javascript">
$(document).ready(function(){
if($("#wrap").size()>0){
if (document.createStyleSheet){
document.createStyleSheet('style.css');
}
else {
$("head").append($("<link rel='stylesheet' href='http://tectrick.org/wp-content/themes/tectrick/style.css' type='text/css' media='screen' />"));
}
}
});
</script>

Method 2 Using Javascript

In this javascript code stylesheet url is ‘http://example/css/bootstrap.min.css’ .  Change this url with your custom url ‘ http://example/css/bootstrap.min.css’.

Example Code

<script>
var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'http://example/css/bootstrap.min.css';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>

Try to paste this code just before </body> tag  .

With this way css load just after loading complete html page . After implement one of the method to load css you can see the change in your pagespeed insight speed .