How much jQuery can the average computer handle without lagging? [closed]
I ask this because I have a jQuery JavaScript file that's getting a tad long now. Also, what's the longest piece of jQuery anyone has ever seen/written?
This is much more dependent on how you write your code, HTML, CSS & JS, and how you configure your server to serve it up.
- Make sure you turn gzip on for your *.html, *.css, *.js (text based files) from your server
- Make sure you set a far-future expiry on your static content (images, etc.)
- Version your CSS/JS files so that you can set a far-future expiry on them to optimize the end-user caching
- Put your JS in the external files, not inline in you HTML as it can't be cached there
- Verify your jQuery/JavaScript code is as optimized as it can be... no extra redundant loops etc.
- Avoid deeply nested tables, or lots of iframes... they hurt your performance.
- In your AJAX calls, if you can... return JSON vs. XML
- Move as much styling as you can into external CSS files, again, this will allow for both caching, and effective re-use
That all said, if you have some sample code we can look at we can give you some better tips.
For example, if you had a <select>
element (drop down) with 1500 <option>
elements in it you might have jQuery like this to get the currently selected value:
var foo = $('#mySelectID > option:selected').attr('value');
Due to the way the jQuery selector is parsed and processed, this may take a long time to find the actual selected option and retrieve its value. On the other hand, this code may run much, much faster.
var foo = document.getElementById('mySelectID').value;
If you have a code sample, it will help us tremendously in providing the most appropriate advice. ;-)
The performance of the jQuery code depends on its quality. For instance, these practices will improve performance:
- caching jQuery objects that are used multiple times, and/or in different handlers, e.g.
var $nav = $("#nav");
- using native API in certain situations, e.g.
this.value
instead of$(this).val()
, andthis.id
instead of$(this).attr("id")
- using delegation to avoid setting to many event handlers (and I don't mean the delegate() method), e.g.
$("#table").click(function(e) { var row = $(e.target).closest("tr")[0]; });
instead of$("#table tr").click(function() { });
- using native loops instead of
$.each()
- using efficient selectors, e.g. ID selectors when available,
$("p.foo")
instead of$(".foo")
- etc.
There are dozens of good practices that improve jQuery performance. Applying these practices is important. The length of the code, not so much.
精彩评论