. By defining a global container with jQuery results, we can reference them from within other functions:

 Arises /searchDsearchfn1search wsearch searchr That s Problem ssearchn Lightsoffnow   Lightsoffnow i Problem hsearchs1fsearchn Tag wsearchjsearchTh Www tsearchcsearchersearchh Tag ansearcht That esearchg Www osearcha Problem   Lightsoffnow c1p That   Arises i Problem e. Arises t Www ewno1 searchb Www e Www t That 
window.$my =
{};

function do_something()
{}

4. Harness the Power of Chaining

The previous example can also be accomplished like this:

var $active_light = $('#traffic_light input.on');$active_light.bind('click', function(){})
.css('border', '3px dashed yellow')
.css('background-color', 'orange')
.fadeIn('slow');

This allows us to write less code, making our JavaScript more lightweight.

5. Use Sub-queries

jQuery allows us to run additional selector operations on a wrapped set. This reduces performance overhead on subsequent selections since we already grabbed and stored the parent object in a local variable.

<div id="content">
<form method="post" action="">
<h2>Traffic Light</h2>
<ul id="traffic_light">
<li><input type="radio" class="on" name="light" value="red" /> Red</li>
<li><input type="radio" class="off" name="light" value="yellow" /> Yellow</li>
<li><input type="radio" class="off" name="light" value="green" /> Green</li>
</ul>
<input class="button" id="traffic_button" type="submit" value="Go" />
</form>
</div>

For example, we can leverage sub-queries to grab the active and inactive lights and cache them for later manipulation.

var $traffic_light = $('#traffic_light'),
$active_light = $traffic_light.find('input.on'),
$inactive_lights = $traffic_light.find('input.off');

Tip: You can declare multiple local variables by separating them with commas – save those bytes!

6. Limit Direct DOM Manipulation

The basic idea here is to create exactly what you need in memory, and then update the DOM. This is not a jQuery best practice, but a must for efficient JavaScript. Direct DOM manipulation is slow. For example, if you need to dynamically create a list of elements, do not do this:

var top_100_list = [...], // assume this has 100 unique strings
$mylist = $('#mylist'); // jQuery selects our <ul> element

for (var i=0, l=top_100_list.length; i<l; i++)
{}

Instead, we want to create the entire set of elements in a string before inserting into the DOM:

var top_100_list = [...], // assume this has 100 unique strings
$mylist = $('#mylist'), // jQuery selects our <ul> element
top_100_li = ""; // This will store our list items

for (var i=0, l=top_100_list.length; i<l; i++)
{}
$mylist.html(top_100_li);

Even faster, we should always wrap many elements in a single parent node before insertion:

var top_100_list = [...], // assume this has 100 unique strings
$mylist = $('#mylist'), // jQuery selects our <ul> element
top_100_ul = '<ul id="#mylist">'; // This will store our entire unordered list

for (var i=0, l=top_100_list.length; i<l; i++)
{}
top_100_ul += '</ul>'; // Close our unordered list

$mylist.replaceWith(top_100_ul);

If you do the above and are still concerned about performance:

7. Leverage Event Delegation (a.k.a. Bubbling)

Unless told otherwise, every event (e.g. click, mouseover, etc.) in JavaScript “bubbles” up the DOM tree to parent elements. This is incredibly useful when we want many elements (nodes) to call the same function. Instead of binding an event listener function to many nodes—very inefficient—you can bind it once to their parent, and have it figure out which node triggered the event. For example, say we are developing a large form with many inputs, and want to toggle a class name when selected. A binding like this is inefficient:

$('#myList li).bind('click', function(){});

Instead, we should listen for the click event at the parent level:

$('#myList).bind('click', function(e){}
});

The parent node acts as a dispatcher and can then do work based on what target element triggered the event. If you find yourself binding one event listener to many elements, you are doing something wrong (and slow).

8. Eliminate Query Waste

Although jQuery fails nicely if it does not find any matching elements, it still takes time to look for them. If you have one global JavaScript for your entire site, it may be tempting to throw every one of your jQuery functions into de<$(document).ready(function(){})de<. Don’t you dare. Only run functions that are applicable to the page. The most efficient way to do this is to use inline initialization functions so your template has full control over when and where JavaScript executes. For example, in your “article” page template, you would include the following code before the body close:

<script type="text/javascript>
mylib.article.init();
</script>
</body>

If your page template includes any variety of modules that may or may not be on the page, or for visual reasons you need them to initialize sooner, you could place the initialization function immediately after the module.

<ul id="traffic_light">
<li><input type="radio" class="on" name="light" value="red" /> Red</li>
<li><input type="radio" class="off" name="light" value="yellow" /> Yellow</li>
<li><input type="radio" class="off" name="light" value="green" /> Green</li>
</ul>
<script type="text/javascript>
mylib.traffic_light.init();
</script>

Your Global JS library would look something like this:

var mylib =
{}
},
traffic_light :
{}
}
}

9. Defer to de<$(window).loadde<

There is a temptation among jQuery developers to hook everything into the de<$(document).readyde< pseudo event. After all, it is used in most examples you will find. Although de<$(document).readyde< is incredibly useful, it occurs during page render while objects are still downloading. If you notice your page stalling while loading, all those de<$(document).readyde< functions could be the reason why. You can reduce CPU utilization during the page load by binding your jQuery functions to the de<$(window).loadde< event, which occurs after all objects called by the HTML (including de<<iframe>de< content) have downloaded.

$(window).load(function(){});

Superfluous functionality such as drag and drop, binding visual effects and animations, pre-fetching hidden images, etc., are all good candidates for this technique.

10. Compress Your JS

Okay, this isn’t jQuery related, but I had to include it. There is a tendency to make JavaScript functions and variables overly descriptive, which is essential for developers but irrelevant to users. No more excuses, it’s time to build JS compression into our workflows. Comment the heck out of your code, and run it through a compression tool before launching to production. Use YUICompressor to squeeze out wasteful bytes from your code. In our experience, it safely compresses JavaScript as small as it can possibly get without a CPU penalty (such as Base62 encoding with Packer). Tip: For maximum compression in YUICompressor, always declare your variables (e.g. var my_long_variable_name;).

11. Learn the Library

Print out this jQuery 1.3 cheat sheet, and make it a goal to eventually understand what each function does. If you find yourself repeating yourself repeating, there is probably an easier (and more efficient) way.

  评论这张
转发至微博
转发至微博
0   分享到:         
阅读(86)| 评论(0)| 引用 (0) |举报
 
 
Javascript HashMap
 
20 Websites to Help You Master User Interface Design

历史上的今天

相关文章

最近读者

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录-->