百度前端面试题3
来源:互联网 发布:算法基础 第5版 编辑:程序博客网 时间:2024/05/21 20:25
3. 请简述javascript延迟加载的方式
答:
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);
};
- 百度前端面试题3
- 百度前端面试题
- 百度前端面试题2
- 一份百度前端面试题:
- 百度-2017前端面试题
- web前端面试题(百度)
- 百度web前端面试题-2015年
- 百度web前端面试题--2014年
- 百度web前端面试题---2014
- 百度前端面试题汇总及答案
- 百度前端面试题错题汇总
- 前端面试题3
- 前端面试题3
- 前端面试题汇总3
- 前端笔试面试题--3
- JOB:前端面试题3
- web前端面试题-各大公司面试题(百度)
- 3-js面试题(前端面试题带答案)
- android Application类的详细介绍
- sql函数:汉字转换为拼音
- How To Find Where The Memory Is Growing For A Process (Doc ID 822527.1)
- 音频编码协议介绍
- 将List集合类转换成DataTable
- 百度前端面试题3
- 第三章、数据预处理
- Cocoa的几种内置数据类型之间的互转
- 关于GNU Linux企业级加密文件系统 eCryptfs介绍
- 我来看蓝汛2014第三季度财报
- Android结束整个应用程序的两个方法
- EL表达式截取字符串以及常见函数使用
- 组合数取模
- 减少VLC 延迟的方法