[·Òë]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´úÂëÈÕ³£ÐÐΪÖÐÖØÒªµÄ×é³É²¿·Ö¡£
 
Ïà¹ØÎĵµ£º
Åжϣ¨value£©ÊÇ·ñÊÇÒ»¸öÊý×Ö£¬¼ÙÈçÖµÊÇNaNÄÇôIsNan·µ»ØTRUE£¬·ñÔò·µ»ØFALSE¡£
»¹ÓÐÒ»ÖÖ°ì·¨£¬±äÁ¿¿ÉÒÔÓëËü×ÔÉí½øÐбȽϡ£ ¼ÙÈç±È½ÏµÄ½á¹û²»µÈ£¬ÄÇôËü¾ÍÊÇ NaN ¡£
ÕâÊÇÒòΪ NaN ÊÇΨһÓë×ÔÉí²»µÈµÄÖµ¡£
µÚÒ»ÖÖ·½·¨£º
<html>
<head>
<title>¼òµ¥¼ÆËãÆ÷µÄÖÆ×÷</title>
</ ......
×òÌ죬ÎÒ±¾À´´òË㣬°ÑÕâ¸ö»°Ìâ½áÊøÁË¡£
µ«ÊÇ£¬Ð´µ½Ò»°ëµÄʱºò£¬ÎÒͻȻÒâʶµ½£¬JavascriptµÄ¼Ì³ÐÓÐÁ½ÖÖ¡£Ò»ÖÖÊÇ»ùÓÚ"º¯Êý¶ÔÏó"µÄ¼Ì³Ð£¬Ò²¾ÍÊÇÒ»¸öfunctionÈ¥¼Ì³ÐÁíÍâÒ»¸öfunction£¬Õâ¸öÎÒÒѾÔÚ×òÌì½éÉܹýÁË¡£
ÁíÒ»ÖÖÔòÊÇ»ùÓÚ"·Çº¯Êý¶ÔÏó"µÄ¼Ì³Ð£¬²»Éæ¼°function¡£ËüµÄ×ö·¨ÓëÇ°Ò»ÖÖÇé¿öÍêÈ«²»Í¬¡£
Ò»¡¢Ê²Ã´ÊÇ"·Çº¯Êý¶ÔÏ ......
×î½ü±àдJavascript´úÂë¡£Æð³õû¹ÜÄÇô¶à¡£Ò»Õó¿ñд¡£´úÂëдµÃ²î²»¶àÁË¡£½á¹ûÉÏ°ÙKÎļþ¼¸Ê®¸ö¡£µ±È» û°ì·¨ÐèҪѹËõÁË¡£ÎªÁËËٶȡ£
ÕÒѹËõ¹¤¾ß¡£ÅªÁËÏ¡£½á¹û´íÎóÒ»´ó¶Ñ¡£×îºó²Å·¢ÏÖÊÇ×Ô¼ºÐ´µÄ´úÂë²»¹æ·¶µ¼Öµġ£¼ì²éÁË°ëÌìÐÞÕýÁ˼¸Ê®¸öµØ·½¡£ÖÕÓÚÄÜѹËõÁË¡£
ÏÂÃæ×ܽáÏÂÐèҪעÒâµÄµØ·½
1¡¢¶ÔÏó½áβ function½áβ ×î ......
1.DOMÊÇÕë¶ÔXMLµÄ»ùÓÚÊ÷µÄAPI¡£Ê¹ÓÃDOM£¬Ö»Ðè½âÎö´úÂëÒ»´ÎÀ´´´½¨Ò»¸öÊ÷µÄÄ£ÐÍ¡£ÔÚÕâ¸ö³õʼ½âÎö¹ý³ÌÖ®ºó£¬XMLÒѾÍêȫͨ¹ýDOMÄ£ÐͱíÏÖ³öÀ´£¬Í¬Ê±Ò²²»ÔÙÐèÒªÔʼµÄ´úÂë¡£
NB
£ºDOMÊÇÓïÑÔÎ޹صÄAPI£¬Ëü²¢²»ÓëJava¡¢JavaScript»òÆäËûÓïÑ԰󶨡£ ......