订阅汇聚素材网Feed

异步加载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>

7 人Likes
  

文章转载请注明:异步加载js,Css方法-汇聚素材网

本文固定链接:http://www.webhj.com/hj-1510.html  +复制链接

异步加载js,Css方法:等您坐沙发呢!

发表评论

*

*

7 + 4

快捷键:Ctrl+Enter
0全站搜索 1 设计 2 素材 3 教材 4 WEB 5 电子书籍