Last active
December 13, 2016 09:51
-
-
Save muthu32/0af5423066b732314a18f27789855efd to your computer and use it in GitHub Desktop.
Defer Loading Javascript & Css in pure javascript & PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
*This library will be used for speeding up website using defer loading of javascript & Css | |
*Made in pure javascript | |
async - javascript will be executed while loading the page. | |
defer - javascript will be executed after loading the page. | |
*/ | |
//To include in Header files | |
$deferJs = "h1:{src:'/javascript/shop_general.js',async:1},h2:{src:'http://www.google-analytics.com/ga.js',async:1}"; | |
$deferCss = "h1:{media:'print',href:'/css/stylePrint.css'}"; | |
//To include in Page files | |
$deferJs .= "p1:{src:'/javascript/page_script.js',defer:1}"; | |
$deferCss .= "p1:{media:'all',href:'/css/stylethispage.css'}"; | |
?> | |
<script type="text/javascript"> | |
function deferLoading() | |
{ | |
var css = {<?php echo isset($deferCss) ? $deferCss : ''; ?>}; | |
var js = {<?php echo isset($deferJs) ? $deferJs : ''; ?>}; | |
//css | |
loadcss(css); | |
//js | |
loadjs(js); | |
} | |
if (window.addEventListener) | |
window.addEventListener("load", deferLoading, false); | |
else if (window.attachEvent) | |
window.attachEvent("onload", deferLoading); | |
else window.onload = deferLoading; | |
function loadjs(js) | |
{ | |
var s = document.getElementsByTagName('head')[0]; | |
for(var key in js){ | |
var ga = document.createElement('script'); ga.type = 'text/javascript'; | |
if (!js.hasOwnProperty(key)) continue; | |
var obj = js[key]; | |
for (var prop in obj) { | |
if(!obj.hasOwnProperty(prop)) continue; | |
switch(prop) | |
{ | |
case 'src': | |
ga.src = obj[prop]; break; | |
case 'async': | |
ga.async = true; break; | |
case 'defer': | |
ga.defer = true; break; | |
} | |
} | |
s.appendChild(ga); | |
} | |
} | |
function loadcss(css) | |
{ | |
var s = document.getElementsByTagName('head')[0]; | |
for(var key in css){ | |
var l = document.createElement('link'); | |
l.type = 'text/css';l.rel = 'stylesheet'; | |
if (!css.hasOwnProperty(key)) continue; | |
var obj = css[key]; | |
for (var prop in obj) { | |
if(!obj.hasOwnProperty(prop)) continue; | |
switch(prop) | |
{ | |
case 'media': | |
l.media = obj[prop]; break; | |
case 'href': | |
l.href = obj[prop]; break; | |
} | |
} | |
s.appendChild(l); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment