Skip to content

Instantly share code, notes, and snippets.

@ziluo
Created December 17, 2013 02:37
Show Gist options
  • Save ziluo/7999068 to your computer and use it in GitHub Desktop.
Save ziluo/7999068 to your computer and use it in GitHub Desktop.
load javascript or css file
function loadFile (url, callback) {
var head = document.getElementsByTagName("head")[0] || document.documentElement
var baseElement = head.getElementsByTagName("base")[0]
var IS_CSS_RE = /\.css(?:\?|$)/i
var currentlyAddingScript
var interactiveScript
var isOldWebKit = +navigator.userAgent
.replace(/.*AppleWebKit\/(\d+)\..*/, "$1") < 536
function request(url, callback) {
var isCSS = IS_CSS_RE.test(url)
var node = document.createElement(isCSS ? "link" : "script")
addOnload(node, callback, isCSS, url)
if (isCSS) {
node.rel = "stylesheet"
node.href = url
} else {
node.async = true
node.src = url
}
currentlyAddingScript = node
baseElement ?
head.insertBefore(node, baseElement) :
head.appendChild(node)
currentlyAddingScript = null
}
function addOnload(node, callback, isCSS, url) {
var supportOnload = "onload" in node
if (isCSS && (isOldWebKit || !supportOnload)) {
setTimeout(function() {
pollCss(node, callback)
}, 1)
return
}
if (supportOnload) {
node.onload = onload
node.onerror = function() {
onload()
}
}
else {
node.onreadystatechange = function() {
if (/loaded|complete/.test(node.readyState)) {
onload()
}
}
}
function onload() {
node.onload = node.onerror = node.onreadystatechange = null
if (!isCSS) {
head.removeChild(node)
}
node = null
callback()
}
}
function pollCss(node, callback) {
var sheet = node.sheet
var isLoaded
if (isOldWebKit) {
if (sheet) {
isLoaded = true
}
} else if (sheet) {
try {
if (sheet.cssRules) {
isLoaded = true
}
} catch (ex) {
if (ex.name === "NS_ERROR_DOM_SECURITY_ERR") {
isLoaded = true
}
}
}
setTimeout(function() {
if (isLoaded) {
callback()
}
else {
pollCss(node, callback)
}
}, 20)
}
function getCurrentScript() {
if (currentlyAddingScript) {
return currentlyAddingScript
}
if (interactiveScript && interactiveScript.readyState === "interactive") {
return interactiveScript
}
var scripts = head.getElementsByTagName("script")
for (var i = scripts.length - 1; i >= 0; i--) {
var script = scripts[i]
if (script.readyState === "interactive") {
interactiveScript = script
return interactiveScript
}
}
}
request(url, callback)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment