我们知道,javascript在执行期时是由内到外执行脚本的,那么离我们的脚本最远的全局对象,很可能要跨越几层作用域才能访问到它。不过在ie中,从最内层到最外层要花的时间比其他多出很多。加之,javascript是一种胶水语言,它必须要调用dom对能完成我们大多数选择。最著名的就是选择元素(document.getelementbyid,document.getelementsbytagname,docuemnt.evaluate,document.queryselector),创建元素(document.createelement),此外还有document.body,document.defaultview.getcomputedstyle等等,频繁地调用document对象,但是document是位于window对象下,因此这路程就更远了。就了提速,我们必须把它们保存在一个本地变量,那么每次就省得它长途跋涉了。这种技术的运用明显体现在jquery的源码中:
(function( window, undefined ) {
// define a local copy of jquery
var jquery = function( selector, context ) {
// the jquery object is actually just the init constructor 'enhanced'
return new jquery.fn.init( selector, context );
},
// map over jquery in case of overwrite
_jquery = window.jquery,
// map over the $ in case of overwrite
_$ = window.$,
// use the correct document accordingly with window argument (sandbox)
document = window.document,
//====================省=================
}
// expose jquery to the global object
window.jquery = window.$ = jquery;
})(window);
把window传进闭包内,就省得它每次都往外找window了。
再看其他类库
//raphael
window.raphael = (function () {
var separator = /[, ]+/,
elements = /^(circle|rect|path|ellipse|text|image)$/,
doc = document,
win = window,
//************略**************
//dojo
d.global = this;
//ext
doc = document,
//yui
//************略************
} else if (i == 'win') {
c[i] = o[i].contentwindow || o[i];
c.doc = c[i].document;
//************略************
y.config = {
win: window || {},
doc: document,
但是如果你没有引入类库,如果让ie的javascript跑得更快些呢?用一个变量把它储存起来?在日本博客看到一种很厉害的劫持技术,偷龙转凤把全局变量document变成一个局部变量。
/*@cc_on _d=document;eval('var document=_d')@*/
="" ="" !!!!!!="" ="" ="">
运行代码
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/