APPENDIX279DOMScriptingLibrariesThroughoutthebookyou'vefocusedonlearningthebasicsoftheDOM.
YouusedthestandardsetofDOMmethodstoperformcommontasksandlearnedhowbesttoapplythosemethodsinyourscripts.
Youmayhavenoticedthatsometimesyourcodewasalittleverboseandrepetitive.
RestrictingyourselftoonlyDOMmethodssuchasdocument.
getElementByIdcangettiring,especiallywhenlibrariesprovidealmostmagicalfunctionslike$thatdoevenmore.
Librariesarepackagesofreusablecodethatofferanumberofadvantages.
Theircodehasbeentestedandprovenbyalargeuserbase.
Theycaneasilyfitintoyourexistingdevelopmentframeworks.
Theyprovidequick,elegantsolutionsformostofyourmundaneday-to-dayDOMscriptingtasks,reducingmultiplelinesofcodedowntoasinglefunction.
Theyprovidecross-browsersolutionssoyoudon'thavetoworryabouteverydifferentbrowser.
Librariesfreeyoutoworkonthegoodstuffinyourapplications,vastlyincreasingyourproductivity.
Theyarewonderful,butusingalibraryisnotthebandageforeveryproblem.
Librariesarecreatedbyothers,notyou.
Thatmeansyoumightnotunderstandwhat'sgoingoninsideanddealingwithbugsorproblemsmaybemoredifficult.
Tousealibrary,youneedtoincludethatlibraryalongwithyourscripts.
Thisaddsanotherrequesttoyourpageloadandmayuseupvaluablebandwidth.
Mixingandmatchinglibrariescanleadtoconflictsoralotofredundantfeatures.
Librariescanalsobecomeacrutchifyouneverventurebeyondthem.
Beforedivingin,besuretotakethetimetoactuallylearnbothJavaScriptandtheDOMasyouhaveinthisbook.
SinceChapter1,I'veemphasizedthenecessityoflearninghowthingsworkandnotsimplywhattheydo.
Therearemanywonderfullibrariesoutthere,someofwhichI'llpointouthere,buthavingnounderstandingofwhat'sgoingonbehindthesceneswillbedetrimentaltobothyouandyourwebapplication.
Withoutthatdeeperunderstanding,you'llbelostinthesmalldetailsthatalibraryoftenassumesyoualreadyknow.
Justtobeclear,I'mnotpersonallyaffiliatedwithanyoftheselibraries,soIhavenopersonalbiastowardsoneortheother.
I'malsonotsayingtheselibrariesareultimatelythebestforeverysituationnoraretheytheonlyonesavailable.
Theseexamplessimplyprovidesomeofthecleanestalternativesolutionsfortasksyou'vealreadyworkedthroughinthebook.
We'regoingtorevisitsomeofthetopicsyou'vealreadyseen,includingthese:SyntaxSelectingelementsAPPENDIXDOMSCRIPTINGLIBRARIES280ManipulatingtheDOMdocumentHandlingeventsAnimationAjaxYou'llseehowlibrariescanhandlethesetasks—oftenwithmuchlesscodeforyou—leavingmoretimetofocusonbusinesslogicinsteadofrepetitiveboringscripting.
NoteEachlibrarycanaccomplishprettymucheverytaskinonewayoranother,soI'llpointoutoneortwomethodsthatIconsiderthebestormostusefulforeacharea—Iwon'tbecoveringeveryaspectofeachlibrary,sobesuretocheckthedocumentationforeachtofindoutwhatelseisavailable.
Beforeyoubegintoworkwithlibraries,it'simportanttochoosetherightone.
Let'slookatafewthingsthatmighthelpyoudecide.
ChoosingalibraryWhenyoudecideit'stimetoinvestigatealibrary,thebiggestproblemischoosingamongthehundredsthatareavailable.
Thereareseveralcriteriayoushouldconsiderinyourdecision:Doesithaveallthefeaturesyou'relookingforMixingandmatchinglibrariescanbeproblematic.
Commonmethodssuchas$()orget()oftenusethesamesyntaxbuthandlethingsdifferently.
Additionally,ifyouusemorethanonelibraryatthesametime,you'llusuallyendupwithalotofduplicatedfeaturesandredundantcode.
DoesithavemorefeaturesthanyouneedHavingtoofewfeaturesisoneproblem,butabulkylibrarywithwaytoomanyisalsoaproblem.
Whenalibraryhasmorefeaturesthanyouneed,oryou'renottakingadvantageofthemall,youmaywanttoconsideralighterversionthatwon'ttakeaslongtodownload.
Thisisespeciallyimportantinmobileenvironments.
IsitmodularLibrarieswithabundantfeaturesoftenworkaroundfilesizebymodularizingfeaturesintodifferentfiles.
Thisletsyouminimizefilesizebyloadingonlythefilesandfeaturesyouneed.
Mostofthetime,you'llhavetobesuretoincludeallthenecessaryfiles,butafewlibrariesmayofferadynamicloadingmechanismwhereyouonlyneedtoincludeonefileandthatfilewillfetchothersasnecessary.
Justbecarefulaboutthenumberofrequestsyouanticipate.
Oftenonelargerequestisbetterthanseveralsmallerones.
IsitwellsupportedLackofanactivedevelopercommunitymeansnobugfixesorfeatureimprovements.
Also,havingmanyeyeslookingatandsharingthesamelibrarymeansfewerbugsandmorereliableresults.
Agoodcommunitybehindthelibrarybringsnotonlyfixesandfeaturesbutalsoalotofsupportwhenyourunintoaproblemandneedmorehelp.
APPENDIXDOMSCRIPTINGLIBRARIES281DoesithavedocumentationWithoutdocumentation,you'llbelost.
Sure,youmightcomeacrosssomeexamplethatothershavehackedtogether,butalackofofficialdocumentationusuallyindicatesalackofenthusiasmbydevelopersandthusaprojectthatmaybegoingnowhere.
DoesithavetherightlicenseJustbecauseyoucanviewthesourceonlinedoesn'tmeanit'sfreeforthetaking.
Beforeusingalibrary,verifythatitslicensecoverswhatyouintendedtodowithitandthatyou'vemetanyspecialrequirements.
Onceyou'vechosenanappropriatelibraryandyou'reproducinggreatthings,don'tforgettotrytocontributebacktothecommunity!
Theselibrariesareallbuiltbydedicateddeveloperswhoareoftenworkingwithwhatlittlesparetimetheyhavetoimprovethetoolsyouusedaily.
Ifyoucan'thelpwithdevelopmenteffortsorbugtesting,youcouldalwaysprovideexamplesandtutorialsorsimplyhelpbuildthedocumentation—anyeffortishelpfulandwillmakethelibraryevenbetter.
AfewlibrariesForthisAppendixI'veselectedafewexamplesbasedontheprecedingcriteriaaswellasgeneralpopularityandabitofpersonalpreference.
MostexamplesusejQuerybutthereareseveralotherlibrarieswithsimilarfeatures.
Eachhasitsownprosandconsasoutlinedhere.
jQuery(http://jquery.
com)describesitselfas"afastandconciseJavaScriptLibrarythatsimplifiesHTMLdocumenttraversing,eventhandling,animating,andAjaxinteractionsforrapidwebdevelopment.
jQueryisdesignedtochangethewaythatyouwriteJavaScript.
"jQuery'sextremelypowerfulselectionmethod,chainingsyntax,andsimplifiedAjaxandeventmethodswillmakeyourcodecompactandeasytofollow.
ThereisalsoaverylargecommunitybehindjQuerywithanumberofdifferentplug-indeveloperswho'veaddedfeaturesbeyondthelibrarybasics.
Prototype(http://prototypejs.
org)describesitselfas"aJavaScriptFrameworkthataimstoeasedevelopmentofdynamicwebapplications.
"PrototypehasanumberofgreatDOM-manipulationfunctionsaswellasoneofthemorepopularAjaxobjects.
ItwasoneofthefirstpopularJavaScriptlibrariesandwasthelibrarythatoriginatedthe$()selectorfunction.
TheYahoo!
UserInterface(YUI)Library(http://developer.
yahoo.
com/yui)describesitselfas"asetofutilitiesandcontrols,writteninJavaScript,forbuildingrichlyinteractivewebapplicationsusingtechniquessuchasDOMscripting,DHTML,andAJAX.
TheYUILibraryalsoincludesseveralcoreCSSresources.
"YUIhasagreatdevelopercommunityandtonsofdocumentation.
ThelibrariesarefilledwitheveryfeatureyoucanthinkoffromsimpleDOMmanipulationtoadvancedeffectsandfullyfeaturedwidgets.
Asawhole,thelibraryisnicelydividedintosmallfilesandnamespacesbutitsometimesbecomesoverwhelmingtryingtodeterminewhatyouneedandwheretofindit—youknowit'sbigwhenjustthecheatsheetisover20pages.
DojoToolkit(http://www.
dojotoolkit.
org/)saysthatit"savesyoutime,deliverspowerfulperformance,andscaleswithyourdevelopmentprocess.
It'sthetoolkitexperienceddevelopersturntoforbuildinggreatwebexperiences.
"Dojoisafull-featuredJavaScripttoolkitusedbyanumberoflargecompanies.
Ithasalargedevelopercommunity,gooddocumentation,andseveralbooksdevotedtoit.
APPENDIXDOMSCRIPTINGLIBRARIES282MooTools(http://mootools.
net/)describesitselfas"acompact,modular,Object-OrientedJavaScriptframeworkdesignedfortheintermediatetoadvancedJavaScriptdeveloper.
Itallowsyoutowritepowerful,flexible,andcross-browsercodewithitselegant,welldocumented,andcoherentAPI.
"MooToolsisextensivelydocumentedandhasalargeusercommunity.
ItnotonlyincludesanumberofgreatDOMenhancementsbutalsointegratestheMoo.
fxeffectslibraryforsimpleandcomplexanimations.
NoteSomelibraries,suchasPrototypeandjQuery,sharethesame$()functionsyntax.
Ifyoudecidetousealibraryinyourproductionenvironment,besuretoreadthedocumentationforyourchosenlibrarytoseehowitmaydifferfromwhatI'mpresentinghereorhowitmayconflictwithotherlibraries.
ContentdeliverynetworksWheneverpossibleyouwanttoreducetheoverallsizeofyourdocumentsandallowthebrowsertocachefilesasmuchaspossible.
Inaddition,youwanttoservethosefilesupasfastaspossible.
Inthecaseoflibraries,ifanumberofdifferentsitesusethesamelibrary,itwouldmakesensetohostthatlibraryinacommonlocationthatallsitescouldaccessandshare.
Thisway,ifusersgofromsitetositetheydon'tneedtodownloadthesamefileoverandoveragain.
Acontentdeliverynetwork(CDN)solvestheproblemofsharedlibrarydistribution.
TheCDNisanetworkofserverswhosesoleresponsibilityisdeliveringcommoncontent.
Theseserverseachcontaincopiesofthelibraryandareplacedatvariousgeographicallocationstomaximizebandwidthandspeed.
BrowserswillaccessalibraryatacommonURLwhiletheunderlyingstructureoftheCDNallowstheclosestandspeediestservertoservethefile,avoidingbottlenecksintheoverallsystem.
GoogleprovidesafreeCDNforanumberoflibraries,includingDojojQueryMooToolsPrototypeYahoo!
UserInterfaceLibrary(YUI)Forafulllistofthemostrecentversionsandthespecificdetailsofeachlibrary,seehttp://code.
google.
com/apis/libraries/devguide.
html.
TouseaCDN,yousimplyincludethelibrarylikeanyotherJavaScriptfile.
Forexample,asofthiswritingthemostrecentGoogleCDNjQueryURLishttps://ajax.
googleapis.
com/ajax/libs/jquery/1.
4.
3/jquery.
min.
js,soyoucanaddthefollowingtoyourdocuments:Ifyou'rehesitanttorelysolelyonGoogleoranotherserviceasyourdistributionnetwork,it'sagoodideatoprovideafailsafefallbacktoalocalfileonyourserverincasetheCDNbecomesunavailable.
Youcansimplychecktoseeiftheappropriateobjectsareloadedandthenincludealocallibraryifnecessary:APPENDIXDOMSCRIPTINGLIBRARIES283!
window.
jQuery&&document.
write(unescape('%3Cscriptsrc="scripts/jquery-1.
4.
3.
min.
js"%3E%3C/script%3E'))NoteThismethodusesdocument.
writetoaddatagtothedocumentifthejQuerylibrarydidn'tcreatetheglobalwindow.
jQueryobject.
The$functionusedelsewhereintheAppendixistheshortformfortheproperjQueryobjectname.
Withthiscodeinplace,iftheservergoesdownitwon'ttakeyoursitewithit.
SyntaxBeforepresentingsomeexamplesIshouldpointoutafewsyntaxoptionsthatmanylibrariesrelyon.
NoteAnumberoflibraries,suchasjQuery,Prototype,MooToolsandothers,offerthedollarsign$()functionasashortcuttotheirselectormethod.
IusethisthroughouttheAppendixsothatthecodeismoregeneric.
Justrememberthatthoughthesyntaxofthefunctioncallsmayappearsimilar,theunderlyingobjectstheycreatearedrasticallydifferent.
Makesureyoureadthedocumentationforyourselectedlibrarytoseehowits$functionworks.
Mostlibrariesoffertheabilityto"chain"methodstogetherusingdotnotation—aperiodjoinsthemethodcalls—similartothewayyou'vealreadyseenwhenusingmethodssuchasgetElemenById:document.
getElementById('example').
nodeName;ThisisafundamentalaspectoflibrariessuchasjQuery,inwhichmethodsarecreatedspecificallytoallowyoutowritecomplicatedscriptsinveryshortchains.
It'snotuncommontoseeone-linescriptsthatdoalotofwork.
Forexample,toremoveandthenaddaclassnametoeveryparagraphinadocumentusingjQuery,youcandothis:$('p').
removeClass('classFoo').
addClass('classBar');That'salotcleanerthantheaddclassfunctionyoucreatedinChapter9.
We'llgetmoreintothat$('p')selectorinamoment.
OneadditionalthingIwillmentionisiteration.
Librariesofferloopingstructuresformanipulatinglistsofelements,andthechainingsyntaxoftenprovidesaverycleanwayofdoingthis.
Forexample,usingjQueryagain,youcanreplicatethisloopfromChapter3:varitems=document.
getElementsByTagName("li");for(vari=0;itagB')selectsalltagBelementsthataredirectchilddescendantsoftagAelements.
$('tagA+tagB')selectsalltagBsiblingelementsthatimmediatelyfollowtagAelements.
$('tagA~tagB')selectsallelementswithaprecedingsiblingtagBelement.
Also,youcanuseseveralpseudo-classandpseudo-elementselectorsincludingthese:$('tag:root')selectsthetagelementthatistherootofthedocument.
$('tag:nth-child(n)')selectsalltagelementsthatarethenthchildrenoftheirparents,countingfromthefirstone.
$('tag:nth-last-child(n)')selectsalltagelementsthatarethenthchildoftheirparents,countingfromthelastone.
$('tag:nth-of-type(n)')selectsalltagelementsthatarethenthsiblingoftheirtype,countingfromthefirstone.
$('tag:nth-last-of-type(n)')selectsalltagelementsthatarethenthsiblingoftheirtype,countingfromthelastone.
$('tag:first-child')selectsanytagelementthatisthefirstchildofitsparents.
$('tag:last-child')selectsanytagelementthatisthelastchildofitsparent.
APPENDIXDOMSCRIPTINGLIBRARIES286$('tag:first-of-type')selectsanytagelementthatisthefirstsiblingofitstype.
$('tag:last-of-type')selectsanytagelementthatisthelastsiblingofitstype.
$('tag:only-child')selectsanytagelementthatisanonlychildofitsparent.
$('tag:only-of-type')selectsanytagelementthatistheonlysiblingofitstype.
$('tag:empty')selectsalltagelementsthathavenochildren.
$('tag:enabled')selectsalluserinterfacetagelementsthatareenabled.
$('tag:disabled')selectsalluserinterfacetagelementsthataredisabled.
$('tag:checked')selectsalluserinterfacetagelementsthatarechecked,suchascheckboxesandradiobuttons.
$('tag:not(s)')selectsalltagelementsthatdon'tmatchtheselectors.
Differentlibrarieshavevaryingsupportforeachselectortype,socheckthedocumentationforyourchosenlibrary.
Withtheseselectors,youcanquicklyaccessveryspecificelementsinyourdocumentsbasedontheirpositionratherthanclassorID.
Thiswillhelpyoukeepyourmarkupfreeofscript-specificIDsandclassesaswellasreduceyourelementselectioncode.
Forexample,youcantakethiscodethatusesDOMmethodstoselectallthelinkswithinnavelementswithinarticles:varlinks=[];vararticles=document.
getElementsByTagName("article");for(vara=0;aNoImagesHereTwohere!
UsingtheYUIYAHOO.
util.
Dom.
getElementBymethod,youcansimplyusetheexistingDOMelementpropertiesyou'veseenearlierinthebooktofilteryourlist:varsingleImageAnchors=YAHOO.
util.
Dom.
getElementsBy(function(e){//Lookfornodeswithonechildimagereturn(e.
nodeName=='A'&&e.
getElementsByTagName('img').
length==1);});APPENDIXDOMSCRIPTINGLIBRARIES289ThesingleImageAnchorsvariablewillcontainalistwithareferenceto,asit'stheonlyanchorwithoneimageasachildintheexamplelist.
PrototypeandjQueryprovidefindAllandfiltermethods,respectively.
Youusetheselasttwointhechainingcontexttofilteroutelementsreturnedfromtheexpression.
First,here'showitlooksinPrototype(usingthe$$selectorfunction)://PrototypelibrarycallbackfiltervarsingleImageAnchors=$$('a').
findAll(function(e){return(e.
descendants().
findAll(function(e){return(e.
nodeName=='IMG');}).
length==1);});Here'sthesamemethodinjQuery://jQuerylibrarycallbackfiltervarsingleImageAnchors=$('a').
filter(function(){return($('img',this).
length==1)});InmostcasesthePrototypeandjQueryexpressionselectorsshouldbeenoughtofilterthelistofelements,butincaseswhereyouneedmorein-depthanalysisoftheelements,callbackscanbeverypowerful.
ManipulatingtheDOMdocumentLibrariesarechock-fullofdifferentDOM-manipulationmethods,asthat'sprettymuchthepointofthelibraryinthefirstplace.
I'lljustpointoutafewandletyouexplorethedocumentationforeachlibrarytofindtherest.
CreatingcontentUsingjQuerytocreatenewDOMelementsisveryeasy.
YoucandefineHTMLastheinputtothe$functiontocreatenodes.
Forexampleherewe'llappendanewdivtothebodyofadocument.
ThedivwillhaveanidofexampleandthecontentofHello:$('Hello
41云怎么样?41云是国人主机品牌,目前经营产品有国内外云服务器、CDN(高防CDN)和物理机,其中国内外云服务器又细分小类有香港限流量VPS、香港大带宽VPS、香港弹性自选VPS、香港不限流VPS、香港BGP线路VPS、香港Cera+大带宽机器、美国超防VPS、韩国原生VPS、仁川原生VPS、日本CN2 VPS、枣庄高防VPS和金华高防VPS;物理机有美国Cera服务器、香港单程CN2服务器、香...
欧路云新上了美国洛杉矶cera机房的云服务器,具备弹性云特征(可自定义需要的资源配置:E5-2660 V3、内存、硬盘、流量、带宽),直连网络(联通CUVIP线路),KVM虚拟,自带一个IP,支持购买多个IP,10G的DDoS防御。付款方式:PayPal、支付宝、微信、数字货币(BTC USDT LTC ETH)测试IP:23.224.49.126云服务器 全场8折 优惠码:zhujiceping...
vollcloud怎么样?vollcloud LLC创立于2020年,是一家以互联网基础业务服务为主的 技术型企业,运营全球数据中心业务。VoLLcloud LLC针对新老用户推出全场年付产品7折促销优惠,共30个,机会难得,所有产品支持3日内无条件退款,同时提供产品免费体验。目前所有产品中,“镇店之宝”产品性价比高,适用大部分用户基础应用,卖的也是最好,同时,在这里感谢新老用户的支持和信任,我们...
jqueryeach为你推荐
nested苹果5恶意win7Singlesb支持ipad支持ipad支持ipad步骤ios重庆宽带测速重庆联通宽带测速的网址是好多呢?ipad连不上wifi苹果ipad突然连不上网了,是怎么回事?网络是好的,手机能上网。360chrome360Chrome 世界之窗极速浏览器 ChromePlus
美国网站空间 河南虚拟主机 视频空间租用 西安电信测速 国内免备案主机 justhost bandwagonhost 优key 香港新世界电讯 免费博客空间 ibrs 免费全能空间 中国智能物流骨干网 怎样建立邮箱 100m空间 美国堪萨斯 ftp免费空间 香港新世界中心 移动服务器托管 万网空间管理 更多