异步加载js,Css方法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Loading Script and Style File</title>
</head>
<body>
<div id="out">
</div>
<script>
//加载ok.css
AsynLoadCss('ok.css','body', function () {
});
//加载jquery
AsynLoadJs('jquery-1.7.1.js','body', function () {
//加载完成后的代码!
$(document).ready(function () {
$("#out").html("加载完成后的代码!");
});
});
//异步加载js方法
function AsynLoadJs(src, target, callback) {
var node = document.createElement('script'),
outEl;
switch (target) {
case 'body':
outEl = document.body;
break;
case 'head':
outEl = document.getElementsByTagName('head')[0];
break;
default:
outEl = document.getElementsByTagName('head')[0];
}
node.type = 'text/javascript';
if (node.addEventListener) {
node.addEventListener('load', callback, false);
node.addEventListener('error', function () {
//error function
}, false);
}
else { // for IE6-8
node.onreadystatechange = function () {
var rs = node.readyState;
if (rs === 'loaded' || rs === 'complete') {
node.onreadystatechange = null;
callback();
}
};
}
node.src = src;
outEl.appendChild(node);
}
//异步加载Css方法
function AsynLoadCss(src, target, callback) {
var node = document.createElement('link'),
outEl;
switch (target) {
case 'body':
outEl = document.body;
break;
case 'head':
outEl = document.getElementsByTagName('head')[0];
break;
default:
outEl = document.getElementsByTagName('head')[0];
}
node.rel = "stylesheet";
node.type = 'text/css';
if (node.addEventListener) {
node.addEventListener('load', callback, false);
node.addEventListener('error', function () {
//error function
//callback();
}, false);
}
else { // for IE6-8
node.onreadystatechange = function () {
var rs = node.readyState;
if (rs === 'loaded' || rs === 'complete') {
node.onreadystatechange = null;
callback();
}
};
}
node.href = src;
outEl.appendChild(node);
}
</script>
</body>
</html>