《学习javascript牛人的讲座视频和课件.ppt》由会员分享,可在线阅读,更多相关《学习javascript牛人的讲座视频和课件.ppt(66页珍藏版)》请在三一办公上搜索。
1、 2006 Douglas Crockford,The Misconceived Web,The original vision of the WWW was as a hyperlinked document-retrieval system.It did not anticipate presentation,session,or interactivity.If the WWW were still consistent with TBLs original vision,Yahoo would still be two guys in a trailer.,How We Got Her
2、e,Rule BreakingCorporate WarfareExtreme Time Pressure,The Miracle,It works!Java didnt.Nor did a lot of other stuff.,The Scripted Browser,Introduced in Netscape Navigator 2(1995)Eclipsed by Java AppletsLater Became the Frontline of the Browser WarDynamic HTMLDocument Object Model(DOM),Proprietary Tra
3、ps,Netscape and LiveWireMicrosoft and Internet Information ServicesBoth server strategies frustrated by ApacheBrowser-dependent sites,Pax Microsoft,In the years since the end of the Browser War,the number of browser variations in significant use fell off significantly.W3C attempts to unify.Mozilla a
4、bandoned the Netscape layer model in favor of the W3C model.The browser platform becomes somewhat stable.DHTML becomes known as Ajax.,Browser,Scripted Browser,The A List,Firefox 1.5Firefox 2.0Safari 2IE 6IE 7Opera 9http:/,Hack for Mosaic and Navigator 1.0.language=javascriptDeprecated.src=URLHighly
5、recommended.Dont put code on pages.type=text/javascriptIgnored.,Script files can have a big impact on page loading time.Place tags as close to the bottom of the body as possible.(Also,place CSS as high in the head as possible.)Minify and gzip script files.Reduce the number of script files as much as
6、 possible.,document.write,Allows JavaScript to produce HTML text.Before onload:Inserts HTML text into the document.After onload:Uses HTML text to replace the current document.Not recommended.,Collections,document.anchorsdocument.appletsdocument.embedsdocument.formsdocument.framesdocument.imagesdocum
7、ent.pluginsdocument.scriptsdocument.stylesheetsAvoid these.,name v id,name=Identifies values in form dataIdentifies a window/frame id=Uniquely identifies an elementThey used to be interchangeable.,document.all,Microsoft feature,rejected by W3C and most other browsers.It acts as a function or array f
8、or accessing elements by position,name,or id.Avoid it.,Retrieving Nodes,document.getElementById(id)document.getElementsByName(name)node.getElementsByTagName(tagName),Document Tree Structure,document,document.body,document.documentElement,child,sibling,parent,child,sibling,parent,child,sibling,parent
9、,child,sibling,parent,Walk the DOM,Using recursion,follow the firstChild node,and then the nextSibling nodes.function walkTheDOM(node,func)func(node);node=node.firstChild;while(node)walkTheDOM(node,func);node=node.nextSibling;,getElementsByClassName,function getElementsByClassName(className)var resu
10、lts=;walkTheDOM(document.body,function(node)var a,c=node.className,i;if(c)a=c.split();for(i=0;i a.length;i+=1)if(ai=className)results.push(node);break;);return results;,childNodes,Manipulating Elements,IMG has these properties:alignnone,top,left,.altstringborderinteger(pixels)heightinteger(pixels)hs
11、paceinteger(pixels)idstringisMapbooleansrcurluseMapurlvspaceinteger(pixels)widthinteger(pixels)node.property=expression;,Manipulating Elements,Old Schoolif(my_plete)my_image.src=superurl;New Schoolif(my_image.getAttribute(complete)my_image.setAttribute(src,superurl);,Style,node.classNamenode.style.s
12、tylenamenode.currentStyle.stylenameOnly IEdocument.defaultView().getComputedStyle(node,).getPropertyValue(stylename);,Style Names,CSSbackground-colorborder-radiusfont-sizelist-style-typeword-spacingz-index,JavaScriptbackgroundColorborderRadiusfontSizelistStyleTypewordSpacingzIndex,Making Elements,do
13、cument.createElement(tagName)document.createTextNode(text)node.cloneNode()Clone an individual element.node.cloneNode(true)Clone an element and all of its descendents.The new nodes are not connected to the document.,Linking Elements,node.appendChild(new)node.insertBefore(new,sibling)node.replaceChild
14、(new,old)old.parentNode.replaceChild(new,old),Removing Elements,node.removeChild(old)It returns the node.Be sure to remove any event handlers.old.parentNode.removeChild(old),innerHTML,The W3C standard does not provide access to the HTML parser.All A browsers implement Microsofts innerHTML property.,
15、Which Way Is Better?,It is better to build or clone elements and append them to the document?Or is it better to compile an HTML text and use innerHTML to realize it?Favor clean code and easy maintenance.Favor performance only in extreme cases.,Events,The browser has an event-driven,single-threaded,a
16、synchronous programming model.Events are targeted to particular nodes.Events cause the invocation of event handler functions.,Mouse Events,The target is the topmost(z-index)node containing the cursor.clickdblclickmousedownmousemovemouseoutmouseovermouseup,Input Events,The target is the node having f
17、ocus.blurchangefocuskeydownkeypresskeyupresetsubmit,Event Handlers,Classicnodeon+type=f;Microsoftnode.attachEvent(on+type,f);W3Cnode.addEventListener(type,f,false);,Event Handlers,The handler takes an optional event parameter.Microsoft does not send an event parameter,use the global event object ins
18、tead.,Event Handlers,function(e)e=e|event;var target=e.target|e.srcElement;.,Trickling and Bubbling,Trickling is an event capturing pattern which provides compatibility with the Netscape 4 model.Avoid it.Bubbling means that the event is given to the target,and then its parent,and then its parent,and
19、 so on until the event is canceled.,Why Bubble?,Suppose you have 100 draggable objects.You could attach 100 sets of event handlers to those objects.Or you could attach one set of event handlers to the container of the 100 objects.,Cancel Bubbling,Cancel bubbling to keep the parent nodes from seeing
20、the event.e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();Or you can use YUIs cancelBubble method.,Prevent Default Action,An event handler can prevent a browser action associated with the event(such as submitting a form).e.returnValue=false;if(e.preventDefault)e.preventDefault();return
21、false;Or you can use YUIs preventDefault method.,Memory Leaks,Memory management is automatic.It is possible to hang on to too much state,preventing it from being garbage collected.,Memory Leaks on IE 6,Explicitly remove all of your event handlers from nodes before you discard them.The IE6 DOM uses a
22、 reference counting garbage collector.Reference counting is not able to reclaim cyclical structures.You must break the cycles yourself.,Memory Leaks on IE 6,That was not an issue for page view-driven applications.It is a showstopper for Ajax applications.It will be fixed in IE7.,Memory Leaks on IE 6
23、,Remove all event handlers from deleted DOM nodes.It must be done on nodes before removeChild or replaceChild.It must be done on nodes before they are replaced by changing innerHTML.,Breaking Links in the DOM,function purgeEventHandlers(node)walkTheDOM(node,function(e)for(var n in e)if(typeof en=fun
24、ction)en=null;);Or you can use YUIs purgeElement method.,JavaScript,alert(text)confirm(text)prompt(text,default)These functions break the asynchronous model.Avoid these in Ajax applications.setTimeout(func,msec)setInterval(func,msec),window,The window object is also the JavaScript global object.Ever
25、y window,frame,and iframe has its own unique window object.aka self.And sometimes parent and top.,Inter-window,framesChild frames and iframesnameText name of windowopenerReference to openparentReference to parent selfReference to this windowtopReference to outermostwindowReference to this windowopen
26、()Open new window,Inter-window,A script can access another window ifIt can get a reference to it.document.domain=otherwindow.document.domainSame Origin Policy,Cross Browser,Weak standards result in significant vendor-specific differences between browsers.Browser Detection.Feature Detection.Platform
27、Libraries.,Browser Detection,Determine what kind of browser that page is running in.Execute conditionally.The browsers lie.navigator.userAgent Mozilla/4.0Brittle.Not recommended.http:/www.mozilla.org/docs/web-developer/sniffer/browser_type.html,Feature Detection,Using reflection,ask if desired featu
28、res are present.Execute conditionally.function addEventHandler(node,type,f)if(node.addEventListener)node.addEventListener(type,f,false);else if(node.attachEvent)node.attachEvent(on+type,f);else nodeon+type=f;,Feature Detection,Using reflection,ask if desired features are present.Execute conditionall
29、y.function addEventHandler(node,type,f)nodeon+type=f;YAHOO.util.Event.addListener(node,type,f);Support for custom events,and for adding events to object that dont exist yet,and for purging event handlers from objects.,Use a Platform Library,A platform library insulates the application from the poiso
30、nous browsers.YUI is highly recommended.http:/,The Cracks of DOM,The DOM buglist includes all of the bugs in the browser.The DOM buglist includes all of the bugs in all supported browsers.No DOM completely implements the standards.Much of the DOM is not described in any standard.,Coping,Do what work
31、s.Do what is common.Do what is standard.,The Wall,Browsers are now being push to their limits.Be prepared to back off.Reduce your memory requirements.Balance of client and server.,The Hole,The browser was not designed to be a general purpose application platform.Lacks a compositing model.Accessibili
32、ty suffers.Lacks support for cooperation under mutual suspicion.,The Peace is ending.,WWW War II,Microsoft has awoken.They are beginning to innovate again.There are now 4 major browser makers.They will be flooding the web with bugs.,We Will Prevail,We must use our clout to keep the browser makers in
33、 line.We must be players,not pawns.We must set the standards.,References,The Document Object Model in Mozillahttp:/www.mozilla.org/docs/dom/MSDN HTML and DHTML Referencehttp:/reference/dhtml_reference_entry.aspIntroduction to Safari JavaScript Programming Topicshttp:/Object Model(DOM)Level 2 Core Specificationhttp:/www.w3.org/TR/DOM-Level-2-Core/,