Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - Is storing jQuery elements in variables more efficient?

Which is more efficient please?

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

or

$("#the-name-of-my-element").doSomethingOnce;
$("#the-name-of-my-element").doSomethingTwice;
...
$("#the-name-of-my-element").doSomethingTenTimes;

I have a page in which the html elements have many varied and sometimes repeated interactions with the JS so I'm wondering if storing the element in a variable prevents multiple jQuery "queries".

As my project is a web app, I'm keen to tune up what I can for the browser.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).

So the winner is:

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...