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
RAKsmart 商家从原本只有专注于独立服务器后看到产品线比较单薄,后来陆续有增加站群服务器、高防服务器、VPS主机,以及现在也有在新增云服务器、裸机云服务器等等。机房也有增加到拥有洛杉矶、圣何塞、日本、韩国、中国香港等多个机房。在年前也有介绍到RAKsmart商家有提供年付129元的云服务器套餐,年后我们看到居然再次刷新年付云服务器低价格。我们看到云服务器低至年79元,如果有需要便宜云服务器的...
ftech怎么样?ftech是一家越南本土的主机商,成立于2011年,比较低调,国内知道的人比较少。FTECH.VN以极低的成本提供高质量服务的领先提供商之一。主营虚拟主机、VPS、独立服务器、域名等传统的IDC业务,数据中心分布在河内和胡志明市。其中,VPS提供1G的共享带宽,且不限流量,还可以安装Windows server2003/2008的系统。Ftech支持信用卡、Paypal等付款,但...
DMIT,最近动作频繁,前几天刚刚上架了日本lite版VPS,正在酝酿上线日本高级网络VPS,又差不多在同一时间推出了美国cn2 gia线路不限流量的美国云服务器,不过价格太过昂贵。丐版只有30M带宽,月付179.99 美元 !!目前美国云服务器已经有个4个套餐,分别是,Premium(cn2 gia线路)、Lite(普通直连)、Premium Secure(带高防的cn2 gia线路),Prem...
jqueryeach为你推荐
投资者适当性客户端系统excursionsios5支持ipad支持ipad支付apple供应商iphonephotoshop技术photoshop技术对哪些工作有用?重庆宽带测速重庆云阳电信宽带测速网址谁知道,帮个忙?联通版iphone4s联通版iPhone4s 用联通3G卡好还是移动的好联通iphone4联通iphone4好用吗
国外虚拟空间 武汉域名注册 阿里云os 地址大全 魔兽世界台湾服务器 html空间 gg广告 umax120 最好的qq空间 ca187 双线asp空间 smtp服务器地址 lamp什么意思 实惠 阿里云邮箱怎么注册 移动王卡 聚惠网 cdn加速 带宽测速 时间同步服务器 更多