[·Òë]High Performance JavaScript(009)
µÚÈýÕ DOM Scripting DOM±à³Ì
DOM scripting is expensive, and it's a common performance bottleneck in rich web applications. This chapter discusses the areas of DOM scripting that can have a negative effect on an application's responsiveness and gives recommendations on how to improve response time. The three categories of problems discussed in the chapter include:
¶ÔDOM²Ù×÷´ú¼Û°º¹ó£¬ÔÚ¸»ÍøÒ³Ó¦ÓÃÖÐͨ³£ÊÇÒ»¸öÐÔÄÜÆ¿¾±¡£±¾ÕÂÌÖÂÛ¿ÉÄܶԳÌÐòÏìÓ¦Ôì³É¸ºÃæÓ°ÏìµÄDOM±à³Ì£¬²¢¸ø³öÌá¸ßÏìÓ¦ËٶȵĽ¨Òé¡£±¾ÕÂÌÖÂÛÈýÀàÎÊÌ⣺
• Accessing and modifying DOM elements
·ÃÎʺÍÐÞ¸ÄDOMÔªËØ
• Modifying the styles of DOM elements and causing repaints and reflows
ÐÞ¸ÄDOMÔªËØµÄÑùʽ£¬Ôì³ÉÖØ»æºÍÖØÐÂÅŰæ
• Handling user interaction through DOM events
ͨ¹ýDOMʼþ´¦ÀíÓû§ÏìÓ¦
But first—what is DOM and why is it slow?
µ«Ê×ÏÈ——ʲôÊÇDOM£¿ËûΪʲôÂý£¿
DOM in the Browser World ä¯ÀÀÆ÷ÊÀ½çÖеÄDOM
The Document Object Model (DOM) is a language-independent application interface (API) for working with XML and HTML documents. In the browser, you mostly work with HTML documents, although it's not uncommon for web applications to retrieve XML documents and use the DOM APIs to access data from those documents.
Îĵµ¶ÔÏóÄ£ÐÍ£¨DOM£©ÊÇÒ»¸ö¶ÀÁ¢ÓÚÓïÑԵģ¬Ê¹ÓÃXMLºÍHTMLÎĵµ²Ù×÷µÄÓ¦ÓóÌÐò½Ó¿Ú£¨API£©¡£ÔÚä¯ÀÀÆ÷ÖУ¬Ö÷ÒªÓëHTMLÎĵµ´ò½»µÀ£¬ÔÚÍøÒ³Ó¦ÓÃÖмìË÷XMLÎĵµÒ²ºÜ³£¼û¡£DOM APIsÖ÷ÒªÓÃÓÚ·ÃÎÊÕâЩÎĵµÖеÄÊý¾Ý¡£
Even though the DOM is a language-independent API, in the browser the interface is implemented in JavaScript. Since most of the work in client-side scripting has to do with the underlying document, DOM is an important part of everyday JavaScript coding.
¾¡¹ÜDOMÊÇÓëÓïÑÔÎ޹صÄAPI£¬ÔÚä¯ÀÀÆ÷ÖеĽӿÚÈ´ÊÇÒÔJavaScriptʵÏֵġ£¿Í»§¶Ë´ó¶àÊý½Å±¾³ÌÐòÓëÎĵµ´ò½»µÀ£¬DOM¾Í³ÉΪJavaScript´úÂëÈÕ³£ÐÐΪÖÐÖØÒªµÄ×é³É²¿·Ö¡£
 
Ïà¹ØÎĵµ£º
±¾ÎÄÖ÷ÒªÊdzöÓÚÓÐÅóÓÑʹÓÃÎÒÔÀ´Ð´µÄautocompleteµÄJS¿Ø¼þ¡£µ±Êý¾ÝÁ¿´óµÄʱºò£¬»á³öÏÖЧÂʼ«ÆäÂýµÄÇé¿ö£¬ÎÒÔÚÕâ¶Îʱ¼ä×ö³öµÄһЩ²âÊÔÒ²¼°Ò»Ð©¾Ñ飬Óë´ó¼Ò·ÖÏí£¬Èç¹ûÓдíµÄµØ·½£¬»¹ÇëÖ¸³ö¡£
¾¹ý²âÊÔ£¬ÎÒÃǻᷢÏÖÈçϵÄÇé¿ö»òÕß˵µÄ½áÂÛ£¬Èç¹ûÄúµÄ²âÊÔ½á¹ûÓëÎҵIJ»·û£¬Çë˵Ã÷ÔÒò£¬ÒÔ±ãÏ໥ѧϰ¡£
1£©µ±Ò»¸ö½Ï´óµÄHTML×Ö· ......
Åжϣ¨value£©ÊÇ·ñÊÇÒ»¸öÊý×Ö£¬¼ÙÈçÖµÊÇNaNÄÇôIsNan·µ»ØTRUE£¬·ñÔò·µ»ØFALSE¡£
»¹ÓÐÒ»ÖÖ°ì·¨£¬±äÁ¿¿ÉÒÔÓëËü×ÔÉí½øÐбȽϡ£ ¼ÙÈç±È½ÏµÄ½á¹û²»µÈ£¬ÄÇôËü¾ÍÊÇ NaN ¡£
ÕâÊÇÒòΪ NaN ÊÇΨһÓë×ÔÉí²»µÈµÄÖµ¡£
µÚÒ»ÖÖ·½·¨£º
<html>
<head>
<title>¼òµ¥¼ÆËãÆ÷µÄÖÆ×÷</title>
</ ......
ÔÚWeb¿ª·¢ÖУ¬»áÓöµ½´ÓÒ»Ò³£¨¸¸Ò³£©µ¼ÏòÁíÒ»Ò³£¨×ÓÒ³£©£¬²¢ÇÒÒªÇó“·µ»Ø”¸¸Ò³µÄÇé¿ö£¬ÔÚÕâÀïÈç¹ûÓÃASP.NETÌṩµÄ Response.Redirect()·½·¨£¬ÍùÍù²»»á´ïµ½ÀíÏëµÄЧ¹û£¬ÀýÈ磺·µ»Øºó£¬ÖØÐ¼ÓÔØÁËÒ³Ãæ£¬ÎÞ·¨±£´æµ¼Ïò×ÓҳǰµÄ״̬£¬µÈµÈ£¬ÔÚÕâÀïÎҾͽéÉÜ Ò»ÏÂÈçºÎʹÓÃJavaScriptÖÐhistory.go()º¯ÊýÀ´ÊµÏÖ·µ»Ø ......
Dynamic Scopes ¶¯Ì¬×÷ÓÃÓò
Both the with statement and the catch clause of a try-catch statement, as well as a function containing eval_r(), are all considered to be dynamic scopes. A dynamic scope is one that exists only through execution of code and therefore cannot be det ......