开发者

storing document in a variable

开发者 https://www.devze.com 2023-02-20 15:16 出处:网络
I just wondered if I stored document into a variable whether there would be a speed enhancement so if I had

I just wondered if I stored document into a variable whether there would be a speed enhancement so if I had

var doc= document;
myElement = doc.getElementById('somethingSweet');

I know in this example it wouldn't make that much different but my thinking is that my variable would act a开发者_如何转开发s a "pointer" to document and so m scripts would not need to try and refer back to document.


There is value in storing something that will be reused in a variable. Document is a poor choice since it's already available on the window. Typically, you would store things that you look up in the document, that aren't already available via top-level properties. This is especially true in functions or plugins that you may develop where you want to keep a reference to the DOM elements that the plugin is operating on handy to avoid looking it up each time.


Document is a global object. How can it be faster to refer to another variable and then to document instead of directly to document? That's a retorical question :)


Wrap your code in a self-executing anonymous function, and pass document as a variable

(function(doc) {
    //code
})(document);

By itself, I don't see any improvements it can make. However, this is a widely used minification technique; minified, doc turns into something like a, so whenever your code uses for example doc.getElementsByTagName, it turns into a.getElementsByTagName.

Edit: A quick example.

//Before minifying
(function(document) {
    var anchor = document.createElement('a');
    anchor.id = 'world';
    document.body.appendChild(anchor);
    document.getElementById('world').innerText = 'Hello World';
})(document);

//After minifying
(function(a){var b=a.createElement("a");b.id="world";a.body.appendChild(b);a.getElementById("world").innerText="Hello World"})(document);

Notice how document turned into "a", and so we saved 7 characters each time! Note that writing obfuscated code isn't suggested, and you should only minify right before shipping out the code.

Minified using the excellent Closure Compiler

0

精彩评论

暂无评论...
验证码 换一张
取 消