Tải bản đầy đủ - 0 (trang)
Chapter 13. JavaScript in Web Browsers

Chapter 13. JavaScript in Web Browsers

Tải bản đầy đủ - 0trang

JavaScriptthathappentobeassociatedwiththeWindow

objectinclient-sideJavaScript.

Chapter15,ScriptingDocuments,explainshowJavaScript

caninteractwiththedocumentcontentdisplayedwithina

webbrowserwindowandhowitcanfind,insert,delete,or

altercontentwithinadocument.

Chapter16,CascadingStyleSheetsandDynamicHTML,

coverstheinteractionofJavaScriptandCSSandshowshow

JavaScriptcodecanalterthepresentationofadocumentby

scriptingCSSstyles,classes,andstylesheets.One

particularlypotentresultofcombiningscriptingwithCSSis

DynamicHTML(orDHTML)inwhichHTMLcontentcanbe

hiddenandshown,moved,andevenanimated.

Chapter17,EventsandEventHandling,explainsevents

andeventhandlingandshowshowJavaScriptadds

interactivitytoawebpagebyallowingittorespondtoa

user'sinput.

Chapter18,FormsandFormElements,coversformswithin

HTMLdocumentsandshowshowJavaScriptcangather,

validate,process,andsubmituserinputwithforms.

Chapter19,CookiesandClient-SidePersistence,showshow

JavaScriptscriptscanpersistentlystoredatausingHTTP

cookies.

Chapter20,ScriptingHTTP,introducesHTTPscripting

(commonlyknownasAjax)anddemonstrateshow

JavaScriptcancommunicatewithwebservers.

Chapter21,JavaScriptandXML,showshowJavaScriptcan

create,load,parse,transform,query,serialize,andextract

informationfromXMLdocuments.



Chapter22,ScriptedClient-SideGraphics,demonstrates

commonJavaScriptimage-manipulationtechniquesthatcan

createimagerolloversandanimationsinwebpages.Italso

demonstratesseveraltechniquesfordynamicallydrawing

vectorgraphicsunderJavaScriptcontrol.

Chapter23,ScriptingJavaAppletsandFlashMovies,

explainshowJavaScriptcaninteractwithJavaappletsand

Flashmoviesembeddedinawebpage.







13.1.TheWebBrowserEnvironment

Tounderstandclient-sideJavaScript,youmustunderstandthe

programmingenvironmentprovidedbyawebbrowser.The

followingsectionsintroducethreeimportantfeaturesofthat

programmingenvironment:

TheWindowobjectthatservesastheglobalobjectand

globalexecutioncontextforclient-sideJavaScriptcode

Theclient-sideobjecthierarchyandtheDocumentObject

Modelthatformsapartofit

Theevent-drivenprogrammingmodel

Thesesectionsarefollowedbyadiscussionoftheproperroleof

JavaScriptinwebapplicationdevelopment.



13.1.1.TheWindowasGlobalExecutionContext

TheprimarytaskofawebbrowseristodisplayHTML

documentsinawindow.Inclient-sideJavaScript,theDocument

objectrepresentsanHTMLdocument,andtheWindowobject

representsthebrowserwindow(orframe)thatdisplaysthe

document.WhiletheDocumentandWindowobjectsareboth

importanttoclient-sideJavaScript,theWindowobjectismore

importantforonesubstantialreason:theWindowobjectisthe

globalobjectinclient-sideprogramming.

RecallfromChapter4thatineveryimplementationof

JavaScriptthereisalwaysaglobalobjectattheheadofthe

scopechain;thepropertiesofthisglobalobjectareglobal

variables.Inclient-sideJavaScript,theWindowobjectisthe



globalobject.TheWindowobjectdefinesanumberof

propertiesandmethodsthatallowyoutomanipulatetheweb

browserwindow.Italsodefinespropertiesthatrefertoother

importantobjects,suchasthedocumentpropertyforthe

Documentobject.Finally,theWindowobjecthastwoselfreferentialproperties,windowandself.Youcanuseeitherglobal

variabletoreferdirectlytotheWindowobject.

SincetheWindowobjectistheglobalobjectinclient-side

JavaScript,allglobalvariablesaredefinedaspropertiesofthe

window.Forexample,thefollowingtwolinesofcodeperform

essentiallythesamefunction:



varanswer=42;//Declareandinitializeaglobalvariabl

window.answer=42;//CreateanewpropertyoftheWindowobj



TheWindowobjectrepresentsawebbrowserwindow(ora

framewithinawindow;inclient-sideJavaScript,top-level

windowsandframesareessentiallyequivalent).Itispossibleto

writeapplicationsthatusemultiplewindows(orframes).Each

windowinvolvedinanapplicationhasauniqueWindowobject

anddefinesauniqueexecutioncontextforclient-sideJavaScript

code.Inotherwords,aglobalvariabledeclaredbyJavaScript

codeinonewindowisnotaglobalvariablewithinasecond

window.However,JavaScriptcodeinthesecondwindowcan

accessaglobalvariableofthefirstwindow,subjecttocertain

securityrestrictions.Theseissuesareconsideredindetailin

Chapter14.



13.1.2.TheClient-SideObjectHierarchyandthe

DOM

TheWindowobjectisthekeyobjectinclient-sideJavaScript.All



otherclient-sideobjectsareaccessedviathisobject.For

example,everyWindowobjectdefinesadocumentpropertythat

referstotheDocumentobjectassociatedwiththewindowanda

locationpropertythatreferstotheLocationobjectassociated

withthewindow.Whenawebbrowserdisplaysaframed

document,theframes[]arrayofthetop-levelWindowobject

containsreferencestotheWindowobjectsthatrepresentthe

frames.Thus,inclient-sideJavaScript,theexpressiondocument

referstotheDocumentobjectofthecurrentwindow;the

expressionframes[1].documentreferstotheDocumentobjectof

thesecondframeofthecurrentwindow.

TheDocumentobject(andotherclient-sideJavaScriptobjects)

alsohavepropertiesthatrefertootherobjects.Forexample,

everyDocumentobjecthasaforms[]arraycontainingForm

objectsthatrepresentanyHTMLformsappearinginthe

document.Torefertooneoftheseforms,youmightwrite:

window.document.forms[0]



Tocontinuewiththesameexample,eachFormobjecthasan

elements[]arraycontainingobjectsthatrepresentthevarious

HTMLformelements(inputfields,buttons,etc.)thatappear

withintheform.Inextremecases,youcanwritecodethat

referstoanobjectattheendofawholechainofobjects,

endingupwithexpressionsascomplexasthisone:

parent.frames[0].document.forms[0].elements[3].options[2].text



Asshownearlier,theWindowobjectistheglobalobjectatthe

headofthescopechain,andallclient-sideobjectsinJavaScript

areaccessibleaspropertiesofotherobjects.Thismeansthat

thereisahierarchyofJavaScriptobjects,withtheWindow



objectatitsroot.Figure13-1showsthishierarchy.



Figure13-1.Theclient-sideobjecthierarchyand

Level0DOM



NotethatFigure13-1showsjusttheobjectpropertiesthat

refertootherobjects.Mostoftheobjectsshowninthediagram

havemethodsandpropertiesotherthanthoseshown.

ManyoftheobjectspicturedinFigure13-1descendfromthe

Documentobject.Thissubtreeofthelargerclient-sideobject

hierarchyisknownasthedocumentobjectmodel(DOM),which

isinterestingbecauseithasbeenthefocusofastandardization

effort.Figure13-1illustratestheDocumentobjectsthathave

becomedefactostandardsbecausetheyareconsistently

implementedbyallmajorbrowsers.Collectively,theyare



knownastheLevel0DOMbecausetheyformabaselevelof

documentfunctionalitythatJavaScriptprogrammerscanrelyon

inallbrowsers.ThesebasicDocumentobjectsarecoveredin

Chapter15,whichalsoexplainsamoreadvanceddocument

objectmodelthathasbeenstandardizedbytheW3C.HTML

formsarepartoftheDOMbutarespecializedenoughthatthey

arecoveredintheirownchapter,Chapter18.



13.1.3.TheEvent-DrivenProgrammingModel

Intheearlydaysofcomputing,computerprogramsoftenranin

batchmode;theyreadinabatchofdata,didsome

computationonthatdata,andthenwroteouttheresults.Later,

withtime-sharingandtext-basedterminals,limitedkindsof

interactivitybecamepossible;theprogramcouldasktheuser

forinput,andtheusercouldtypeindata.Thecomputerthen

processedthedataanddisplayedtheresultsonscreen.

Nowadays,withgraphicaldisplaysandpointingdevicessuchas

mice,thesituationisdifferent.Programsaregenerallyeventdriven;theyrespondtoasynchronoususerinputintheformof

mouseclicksandkeystrokesinawaythatdependsonthe

positionofthemousepointer.Awebbrowserisjustsucha

graphicalenvironment.AnHTMLdocumentcontainsan

embeddedgraphicaluserinterface(GUI),soclient-side

JavaScriptusestheevent-drivenprogrammingmodel.

ItisperfectlypossibletowriteastaticJavaScriptprogramthat

doesnotacceptuserinputanddoesexactlythesamething

everytimeitisrun.Sometimesthissortofprogramisuseful.

Moreoften,however,you'llwanttowritedynamicprograms

thatinteractwiththeuser.Todothis,youmustbeableto

respondtouserinput.

Inclient-sideJavaScript,thewebbrowsernotifiesprogramsof

userinputbygeneratingevents.Therearevarioustypesof



events,suchaskeystrokeevents,mousemotionevents,andso

on.Whenaneventoccurs,thewebbrowserattemptstoinvoke

anappropriateeventhandlerfunctiontorespondtotheevent.

Thus,towritedynamic,interactiveclient-sideJavaScript

programs,youmustdefineappropriateeventhandlersand

registerthemwiththesystem,sothatthebrowsercaninvoke

thematappropriatetimes.

Ifyouarenotalreadyaccustomedtotheevent-driven

programmingmodel,itcantakealittlegettingusedto.Inthe

oldmodel,youwroteasingle,monolithicblockofcodethat

followedsomewell-definedflowofcontrolandranto

completionfrombeginningtoend.Event-drivenprogramming

standsthismodelonitshead.Inevent-drivenprogramming,

youwriteanumberofindependent(butmutuallyinteracting)

eventhandlers.Youdonotinvokethesehandlersdirectlybut

allowthesystemtoinvokethemattheappropriatetimes.Since

theyaretriggeredbytheuser'sinput,thehandlersareinvoked

atunpredictable,asynchronoustimes.Muchofthetime,your

programisnotrunningatallbutmerelysitting,waitingforthe

systemtoinvokeoneofitseventhandlers.

ThesectionsthatfollowexplainhowJavaScriptcodeis

embeddedwithinHTMLfiles.Itshowshowtodefinebothstatic

blocksofcodethatrunsynchronouslyfromstarttofinishand

eventhandlersthatareinvokedasynchronouslybythesystem.

EventsandeventhandlingarediscussedagaininChapter15,

andtheneventsarecoveredindetailinChapter17.



13.1.4.TheRoleofJavaScriptontheWeb

Theintroductiontothischapterincludedalistoftheweb

browsercapabilitiesthatcanbescriptedwithclient-side

JavaScript.Note,however,thatlistingwhatJavaScriptcanbe

usedforisnotthesameasexplainingwhatJavaScriptoughtto

beusedfor.Thissectionattemptstoexplaintheproperroleof



JavaScriptinwebapplicationdevelopment.

WebbrowsersdisplayHTML-structuredtextstyledwithCSS

stylesheets.HTMLdefinesthecontent,andCSSsuppliesthe

presentation.Properlyused,JavaScriptaddsbehaviortothe

contentanditspresentation.TheroleofJavaScriptisto

enhanceauser'sbrowsingexperience,makingiteasierto

obtainortransmitinformation.Theuser'sexperienceshouldnot

bedependentonJavaScript,butJavaScriptcanserveto

facilitatethatexperience.JavaScriptcandothisinanynumber

ofways.Herearesomeexamples:

Creatingvisualeffectssuchasimagerolloversthatsubtly

guideauserandhelpwithpagenavigation

Sortingthecolumnsofatabletomakeiteasierforauser

tofindwhatheneeds

Hidingcertaincontentandrevealingdetailsselectivelyas

theuser"drillsdown"intothatcontent

Streamliningthebrowsingexperiencebycommunicating

directlywithawebserversothatnewinformationcanbe

displayedwithoutrequiringacompletepagereload



13.1.5.UnobtrusiveJavaScript

Anewclient-sideprogrammingparadigmknownasunobtrusive

JavaScripthasbeengainingcurrencywithintheweb

developmentcommunity.Asitsnameimplies,thisparadigm

holdsthatJavaScriptshouldnotdrawattentiontoitself;it

shouldnotobtrude.[*]Itshouldnotobtrudeonusersviewinga

webpage,oncontentauthorscreatingHTMLmarkup,oron

webdesignerscreatingHTMLtemplatesorCSSstylesheets.



[*]"Obtrude"isanobscuresynonymfor"intrude."TheAmericanHeritagedictionarycites:"Toimpose...on

otherswithundueinsistenceorwithoutinvitation."



ThereisnospecificformulaforwritingunobtrusiveJavaScript

code.However,anumberofhelpfulpractices,discussed

elsewhereinthisbook,willputyouontherighttrack.

ThefirstgoalofunobtrusiveJavaScriptistokeepJavaScript

codeseparatefromHTMLmarkup.Thiskeepscontentseparate

frombehaviorinthesamewaythatputtingCSSinexternal

stylesheetskeepscontentseparatefrompresentation.To

achievethisgoal,youputallyourJavaScriptcodeinexternal

filesandincludethosefilesintoyourHTMLpageswith
src=>tags(seeSection13.2.2.fordetails).Ifyouarestrict

abouttheseparationofcontentandbehavior,youwon'teven

includeJavaScriptcodeintheevent-handlerattributesofyour

HTMLfiles.Instead,youwillwriteJavaScriptcode(inan

externalfile)thatregisterseventhandlersontheHTML

elementsthatneedthem(Chapter17describeshowtodothis).

Asacorollarytothisgoal,youshouldstrivetomakeyour

externalfilesofJavaScriptcodeasmodularaspossibleusing

techniquesdescribedinChapter10.Thisallowsyoutoinclude

multipleindependentmodulesofcodeintothesamewebpage

withoutworryingaboutthevariablesandfunctionsofone

moduleoverwritingthevariablesandfunctionsofanother.

ThesecondgoalofunobtrusiveJavaScriptisthatitmust

degradegracefully.Yourscriptsshouldbeconceivedand

designedasenhancementstoHTMLcontent,butthatcontent

shouldstillbeavailablewithoutyourJavaScriptcode(aswill

happen,forexample,whenauserdisablesJavaScriptinher

browser).Animportanttechniqueforgracefuldegradationis

calledfeaturetesting:beforetakinganyactions,your

JavaScriptmodulesshouldfirstensurethattheclient-side

featurestheyrequireareavailableinthebrowserinwhichthe

codeisrunning.Featuretestingisacompatibilitytechnique

describedinmoredetailinSection13.6.3.



AthirdgoalofunobtrusiveJavaScriptisthatitmustnot

degradetheaccessibilityofanHTMLpage(andideallyitshould

enhanceaccessibility).IftheinclusionofJavaScriptcode

reducestheaccessibilityofwebpages,thatJavaScriptcodehas

obtrudedonthedisableduserswhorelyonaccessibleweb

pages.JavaScriptaccessibilityisdescribedinmoredetailin

Section13.7.

OtherformulationsofunobtrusiveJavaScriptmayincludeother

goalsinadditiontothethreedescribedhere.Oneprimary

sourcefromwhichtolearnmoreaboutunobtrusivescriptingis

"TheJavaScriptManifesto,"publishedbytheDOMScripting

TaskForceathttp://domscripting.webstandards.org/?

page_id=2.







Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 13. JavaScript in Web Browsers

Tải bản đầy đủ ngay(0 tr)

×