Created
October 26, 2017 07:55
-
-
Save rolandtoth/09dc97fa1eb5c7af09849f738160411a to your computer and use it in GitHub Desktop.
loadAsset.js CSS/Js loader
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
function loadAsset(path, callback, o) { | |
var selector = getUrlParameter('selector', path).replace(/['"]+/g, '').trim(), | |
async = getUrlParameter('async', path) === 'true', | |
version = getUrlParameter('v', path), | |
assetType = 'js', | |
assetTag = 'script', | |
assetSrc = 'src', | |
needAsset = true; | |
if (selector.length > 0 && !document.querySelector(selector)) | |
return false; | |
if (version.length) { | |
version = '?v=' + version; | |
} | |
function getUrlParameter(name, url) { | |
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); | |
url = url ? url : window.location.search; | |
// var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'), | |
var regex = new RegExp('[\\?&]' + name + '=([^&]*)'), | |
results = regex.exec(url); | |
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); | |
} | |
path = path.split(/\?(.+)/)[0]; // remove url parameters (settings) | |
if (path.slice(-3) === 'css') { | |
assetType = 'css'; | |
assetTag = 'link'; | |
assetSrc = 'href'; | |
} | |
if (document.querySelector(assetTag + '[' + assetSrc + '="' + path + '"]')) | |
needAsset = false; | |
function callCallback() { | |
if (callback) { | |
var obj = {}; | |
if (selector) | |
obj.selector = selector; | |
if (o) | |
obj.o = o; | |
callback.call(obj); | |
} | |
} | |
if (needAsset) { | |
var asset = document.createElement(assetTag); | |
asset[assetSrc] = path + version; | |
if (assetType === 'js') { | |
asset.type = "text/javascript"; | |
asset.async = async; | |
if (asset.readyState) { // IE | |
asset.onreadystatechange = function () { | |
if (asset.readyState === "loaded" || asset.readyState === "complete") { | |
asset.onreadystatechange = null; | |
callCallback(); | |
} | |
}; | |
} else { // others | |
asset.onload = callCallback; | |
} | |
} else { // CSS | |
asset.rel = "stylesheet"; | |
callCallback(); | |
} | |
document.getElementsByTagName("head")[0].appendChild(asset); | |
} else { // always run callback | |
callCallback(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment