JS、CSS、Image预加载

Image预加载

<div class="hidden">
<script type="text/javascript">

var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"./images/icon-1.png",
"./images/icon-2.png",
"./images/icon-4.png",
"./images/icon-5.png",
"./images/icon-3.png",
"./images/icon-6.png",
"./images/icon-7.png",
"./images/icon-8.png",
"./images/icon-9.png",
"./images/icon-10.png",
"./images/icon-11.png",
"./images/icon-12.png",
"./images/icon-13.png",
"./images/icon-14.png",
"./images/icon-15.png",
"./images/icon-16.png",
"./images/icon-17.png",
"./images/icon-18.png",
"./images/icon-19.png",
"./images/icon-20.png",

)
</script>
</div>

JS

function loadScript(src,fn){
var node = document.createElement("script");
node.setAttribute('async','async');
var timeID
var supportLoad = "onload" in node
var onEvent = supportLoad ? "onload" : "onreadystatechange"
node[onEvent] = function onLoad() {
if (!supportLoad && !timeID && /complete|loaded/.test(node.readyState)) {
timeID = setTimeout(onLoad)
return
}
if (supportLoad || timeID) {
clearTimeout(timeID)
fn(null,node);
}
}
document.head.insertBefore(node, document.head.firstChild);
node.src=src;
node.onerror=function(e){
fn(e);
}
}
loadScript("test.js",fail);

CSS

function loadCss(src,fn){
var node=document.createElement('link');
node.rel='stylesheet';
node.href=src;
document.head.insertBefore(node,document.head.firstChild);
if(node.attachEvent){
node.attachEvent('onload', function(){fn(null,node)});
}else{
setTimeout(function() {
poll(node, fn);
}, 0); // for cache
}
function poll(node,callback){
var isLoaded = false;
if(/webkit/i.test(navigator.userAgent)) {//webkit
if (node['sheet']) {
isLoaded = true;
}
}else if(node['sheet']){// for Firefox
try{
if (node['sheet'].cssRules) {
isLoaded = true;
}
}catch(ex){
// NS_ERROR_DOM_SECURITY_ERR
if (ex.code === 1000) {
isLoaded = true;
}
}
}
if(isLoaded){
setTimeout(function(){
callback(null,node);
},1);
}else{
setTimeout(function(){
poll(node,callback);
},10);
}
}
node.onLoad=function(){
fn(null,node);
}
}

JS

function loadScript(src,fn) {
var node = document.createElement("script");
node.setAttribute('async','async');
var timeID
var supportLoad = "onload" in node
var onEvent = supportLoad ? "onload": "onreadystatechange"
node[onEvent] = function onLoad() {
if (!supportLoad && !timeID && /complete|loaded/.test(node.readyState)) {
timeID = setTimeout(onLoad)
return
}

if (supportLoad || timeID) {
clearTimeout(timeID)
fn(null,node);
}
}

document.head.insertBefore(node, document.head.firstChild);
node.src=src;
node.onerror=function(e) {
fn(e);
}
}

猜你喜欢

转载自www.cnblogs.com/xieyongbin/p/10027997.html