The arrival of jQuery makes the process of writing JavaScript extremely simple. However, you'll notice that making small changes to your code can significantly improve readability and/or performance. Here are some tips to help you optimize your code.
We need a reliable platform for testing. Here is the HTML markup for the test page where we will run all the tests:
<!DOCTYPE html> <html lang="en-GB"> <head> <title>Testing out performance enhancements - Siddharth/NetTuts+</title> </head> <body> <div id="container"> <div class="block"> <p id="first"> Some text here </p> <ul id="someList"> <li class="item"></li> <li class="item selected" id="mainItem">Oh, hello there!</li> <li class="item"></li> <li class="item"></li> </ul> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script> console.profile() ; // Our code here console.profileEnd(); </script> </body> </html>
Nothing fancy here; just a bunch of elements we can target and test. We use Firebug to log the time here. profile starts the process, profileEnd stops the process, and records the time spent on the task. I usually use Firebug's main profile method, but for our nefarious purposes this will suffice.
Typically, you will provide a single script file containing code to all pages in your site. This is usually code that frequently performs operations on elements that do not exist on the current page. Although jQuery handles such issues very gracefully, that doesn't mean you can ignore any issues. In fact, if you call jQuery's methods on an empty collection, they won't run.
As a best practice, only run code that applies to the currently loaded page, rather than lumping all code into a single document readiness check and serving it to the client.
Let’s look at the first scene:
console.profile(); var ele = $("#somethingThatisNotHere"); ele.text("Some text").slideUp(300).addClass("editing"); $("#mainItem"); console.profileEnd(); //Some more awesome, ground shattering code here ._.
Firebug outputs the following results:
This time, we check whether the element to be operated on exists before performing the operation.
console.profile() ; var ele = $("#somethingThatisNotHere"); if ( ele[0] ) { ele.text("Some text").slideUp(300).addClass("editing"); } $("#mainItem"); console.profileEnd(); //Some more awesome, ground shattering code here ._.
result:
see it? It's very simple, to the point and gets the job done. Please note that you do not need to check whether the element is present at every bit of the code. You'll notice that certain larger sections of the page often benefit from this approach. Use your judgment here.
Try using ID instead of passing class.
This is a big topic, so I'll try to be as concise as possible. First, when passing the selector, try using the ID instead of passing the class. jQuery directly uses the native getElementById method to find an element by ID, whereas with a class it has to perform some internal wizardry to get it, at least in older browsers.
We will look at the different selectors that can be used to target the second li element. We'll test each of them and how they change performance.
The first way, and the simplest way, is to target it explicitly using the selected class. Let’s see what Firebug’s profiler returns.
console.profile() ; $(".selected"); console.profileEnd();
Result: 0.308ms. Next, we add a prefix to the tag name to narrow it down. This way we can narrow the search by first targeting only the selected DOM elements using document.getElementsByTagName.
console.profile() ; $("li.selected"); console.profileEnd();
Result: 0.291ms. That's about 0.02 milliseconds shorter. Since we were testing in Firefox, this is negligible; however, it should be noted that this performance gain is significantly higher in older browsers such as Internet Explorer 6.
Next, we start from the ID of the parent element and descend.
console.profile() ; $("#someList .selected"); console.profileEnd();
Result: 0.283ms. Let's try to be a little more specific. In addition to the ID of the ancestor, we also specify the type of the element.
console.profile() ; $("#someList li.selected"); console.profileEnd();
Result: 0.275 milliseconds. A small part was shaved off. Finally, we use the ID directly to locate it.
console.profile() ; $("#mainItem"); console.profileEnd();
Result: 0.165ms. touching! This really shows you how fast running native methods can be. Note that while modern browsers can take advantage of features like getElementsByClassName, older browsers cannot - resulting in significantly slower performance. Always consider this when coding.
Sizzle, the selector engine used by jQuery - built by John Resig - parses selectors from right to left, which can lead to some unexpected parsing chains.
Consider this selector:
$("#someList .selected");
当Sizzle遇到这样的选择器时,它首先构建DOM结构,使用选择器作为根,丢弃不具有所需类的项目,并且对于具有该类的每个元素,它检查其父元素是否具有ID 为 someList。
为了解决这个问题,请确保选择器最右侧的部分尽可能具体。例如,通过指定 li.selected 而不是 .selected,您可以减少必须检查的节点数量。这就是上一节中性能跳跃的原因。通过添加额外的约束,您可以有效地减少必须检查的节点数量。
为了更好地调整元素的获取方式,您应该考虑为每个请求添加上下文。
var someList = $('#someList')[0]; $(".selected", someList);
通过添加上下文,搜索元素的方式完全改变。现在,首先搜索提供上下文的元素(在我们的示例中为 someList),一旦获得该元素,就会删除不具有必需类的子元素。
请注意,将 DOM 元素作为 jQuery 选择器的上下文传递通常是最佳实践。当上下文存储在某个变量中时,使用上下文是最有帮助的。否则,您可以简化该过程并使用 find() —— jQuery 本身就是在幕后做的。
$('#someList').find('.selected');
我想说性能提升将会被明确定义,但我不能。我已经在许多浏览器上运行了测试,范围方法的性能是否优于普通版本取决于许多因素,包括浏览器是否支持特定方法。
当您浏览别人的代码时,您经常会发现。
// Other code $(element).doSomething(); // More code $(element).doSomethingElse(); // Even more code $(element).doMoreofSomethingElse();
请不要这样做。 永远。开发人员一遍又一遍地实例化这个“元素”。这是浪费。
让我们看看运行这样可怕的代码需要多长时间。
console.profile() ; $("#mainItem").hide(); $("#mainItem").val("Hello"); $("#mainItem").html("Oh, hey there!"); $("#mainItem").show(); console.profileEnd();
如果代码的结构如上所示,一个接一个,您可以像这样使用链接:
console.profile(); $("#mainItem").hide().val("Hello").html("Oh, hey there!").show(); console.profileEnd();
通过链接,获取最初传入的元素,并将引用传递给每个后续调用,从而减少执行时间。否则每次都会创建一个新的 jQuery 对象。
但是,如果与上面不同,引用该元素的部分不是并发的,则您必须缓存该元素,然后执行与以前相同的所有操作。
console.profile() ; var elem = $("#mainItem"); elem.hide(); //Some code elem.val("Hello"); //More code elem.html("Oh, hey there!"); //Even more code elem.show(); console.profileEnd();
从结果中可以明显看出,缓存或链接大大减少了执行时间。
我之前的文章中建议进行非传统 DOM 操作,但在被证明性能提升确实值得之前,遭到了一些人的批评。我们现在将亲自测试一下。
对于测试,我们将创建 50 个 li 元素,并将它们附加到当前列表,并确定需要多少时间。
我们将首先回顾一下正常的、低效的方法。我们实质上是在每次循环运行时将元素附加到列表中。
console.profile() ; var list = $("#someList"); for (var i=0; i<50; i++) { list.append('<li>Item #' + i + '</li>'); } console.profileEnd();
让我们看看效果如何,好吗?
现在,我们将走一条稍微不同的道路。我们首先会将所需的 HTML 字符串附加到变量中,然后仅回流 DOM 一次。
console.profile() ; var list = $("#someList"); var items = ""; for (var i=0; i<50; i++){ items += '<li>Item #' + i + '</li>'; } list.append(items); console.profileEnd();
正如预期的那样,所花费的时间显着减少。
如果您使用 jQuery 作为 getElementById 的替代品,但从未使用它提供的任何方法,那么您就做错了。
如果您想更进一步,问问自己是否真的需要创建一个新的 jQuery 对象来定位某些元素?如果您使用 jQuery 作为 document.getElementById 的替代品,但从未使用它提供的任何方法,那么您就做错了。在这种情况下,我们可以使用原始 JS。
console.profile() ; var list = document.getElementById('someList'); var items = ''; for (var i=0; i<50; i++){ items += '<li>Item #' + i + '</li>'; } list.innerHTML = items; console.profileEnd();
您会注意到优化代码和未优化代码之间的执行时间差异只有几分之一毫秒。这是因为我们的测试文档非常小,节点数量少得令人难以置信。一旦您开始使用包含数千个节点的生产级站点,它就会真正增加。
另请注意,在大多数测试中,我只是访问元素。当您开始对它们应用适当的函数时,执行时间的增量将会增加。
我也明白这不是测试性能的最科学的方法,但是,为了大致了解这些变化对性能的影响程度,我认为这已经足够了。
Finally, in most web applications, the connection speed and response time of the associated web server has a greater impact on application performance than adjustments to the code. Still, this is important information, and it will help you when you're trying to get as much performance as possible from your code.
We're done. Here are a few things to keep in mind when you're trying to optimize your code; of course, this isn't an exhaustive list of tweaks, and these points won't necessarily apply in every situation. Either way, I'll be keeping an eye on the comments to read your thoughts on this topic. Do you see anything wrong here? Please leave me a comment below.
Have questions? Have something nice to say? criticize? Hit the comments section and leave me a message. Happy coding!
The above is the detailed content of Test and enhance jQuery code for beginners. For more information, please follow other related articles on the PHP Chinese website!