延迟加载javascript,也就是页面加载完成之后再加载javascript,也叫on demand(按需)加载,一般有一下几个方法:
1. dom
head append script tag
window.onload = function() {
settimeout(function(){
// reference to <head>
var head = document.getelementsbytagname('head')[0];
// a new css
var css = document.createelement('link');
css.type = "text/css";
css.rel = "stylesheet";
css.href = "new.css";
// a new js
var js = document.createelement("script");
js.type = "text/javascript";
js.src = "new.js";
// preload js and css
head.appendchild(css);
head.appendchild(js);
// preload image
new image().src = "new.png";
}, 1000);
};2. document.write
<script language="javascript" type="text/javascript">
function include(script_filename) {
document.write('<' + 'script');
document.write(' language="javascript"');
document.write(' type="text/javascript"');
document.write(' src="' + script_filename + '">');
document.write('</' + 'script' + '>');
}
var which_script = '1.js';
include(which_script);
</script>3. iframe
和第一种类似,但是script tag是放到iframe的document里面。
window.onload = function() {
settimeout(function(){
// create new iframe
var iframe = document.createelement('iframe');
iframe.setattribute("width", "0");
iframe.setattribute("height", "0");
iframe.setattribute("frameborder", "0");
iframe.setattribute("name", "preload");
iframe.id = "preload";
iframe.src = "about:blank";
document.body.appendchild(iframe);
// gymnastics to get reference to the iframe document
iframe = document.all ? document.all.preload.contentwindow : window.frames.preload;
var doc = iframe.document;
doc.open(); doc.writeln("<html><body></body></html>"); doc.close();
// create css
var css = doc.createelement('link');
css.type = "text/css";
css.rel = "stylesheet";
css.href = "new.css";
// create js
var js = doc.createelement("script");
js.type = "text/javascript";
js.src = "new.js";
// preload css and js
doc.body.appendchild(css);
doc.body.appendchild(js);
// preload img
new image().src = "new.png";
}, 1000);
};4. iframe static page
直接把需要加载东西放到另一个页面中
window.onload = function() {
settimeout(function(){
// create a new frame and point to the url of the static
// page that has all components to preload
var iframe = document.createelement('iframe');
iframe.setattribute("width", "0");
iframe.setattribute("height", "0");
iframe.setattribute("frameborder", "0");
iframe.src = "preloader.html";
document.body.appendchild(iframe);
}, 1000);
};5. ajax eval
用ajax下载代码,然后用eval执行
6. ajax injection
用ajax下载代码,建立一个空的script tag,设置text属性为下载的代码
7. async 属性(缺点是不能控制加载的顺序)
<script src="" async="true"/>
到此这篇关于javascript中延迟加载的7种方法实现的文章就介绍到这了,更多相关javascript 延迟加载内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论