关闭

关闭

关闭

封号提示

内容

首页 高性能JavaScript.pdf

高性能JavaScript.pdf

高性能JavaScript.pdf

魔域私服 2011-06-14 评分 0 浏览量 0 0 0 0 暂无简介 简介 举报

简介:本文档为《高性能JavaScriptpdf》,可适用于IT/计算机领域,主题内容包含HighPerformanceJavaScriptHighPerformanceJavaScriptNicholasCZakasBeijing•Ca符等。

HighPerformanceJavaScriptHighPerformanceJavaScriptNicholasCZakasBeijing•Cambridge•Farnham•Köln•Sebastopol•Taipei•TokyoHighPerformanceJavaScriptbyNicholasCZakasCopyrightYahoo!,IncAllrightsreservedPrintedintheUnitedStatesofAmericaPublishedbyO’ReillyMedia,Inc,GravensteinHighwayNorth,Sebastopol,CAO’Reillybooksmaybepurchasedforeducational,business,orsalespromotionaluseOnlineeditionsarealsoavailableformosttitles(http:mysafaribooksonlinecom)Formoreinformation,contactourcorporateinstitutionalsalesdepartment:()orcorporateoreillycomEditor:MaryETreselerProductionEditor:AdamZarembaCopyeditor:Genevieved’EntremontProofreader:AdamZarembaIndexer:FredBrownCoverDesigner:KarenMontgomeryInteriorDesigner:DavidFutatoIllustrator:RobertRomanoPrintingHistory:March:FirstEditionNutshellHandbook,theNutshellHandbooklogo,andtheO’ReillylogoareregisteredtrademarksofO’ReillyMedia,IncHighPerformanceJavaScript,theimageofashortearedowl,andrelatedtradedressaretrademarksofO’ReillyMedia,IncManyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarksWherethosedesignationsappearinthisbook,andO’ReillyMedia,Incwasawareofatrademarkclaim,thedesignationshavebeenprintedincapsorinitialcapsWhileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisherandauthorassumenoresponsibilityforerrorsoromissions,orfordamagesresultingfromtheuseoftheinformationcontainedhereinTMThisbookusesRepKover,adurableandflexiblelayflatbindingISBN:MThisbookisdedicatedtomyfamily,Mom,Dad,andGreg,whoseloveandsupporthavekeptmegoingthroughtheyearsTableofContentsPrefacexiLoadingandExecutionScriptPositioningGroupingScriptsNonblockingScriptsDeferredScriptsDynamicScriptElementsXMLHttpRequestScriptInjectionRecommendedNonblockingPatternSummaryDataAccessManagingScopeScopeChainsandIdentifierResolutionIdentifierResolutionPerformanceScopeChainAugmentationDynamicScopesClosures,Scope,andMemoryObjectMembersPrototypesPrototypeChainsNestedMembersCachingObjectMemberValuesSummaryDOMScriptingDOMintheBrowserWorldInherentlySlowDOMAccessandModificationinnerHTMLVersusDOMmethodsviiCloningNodesHTMLCollectionsWalkingtheDOMRepaintsandReflowsWhenDoesaReflowHappenQueuingandFlushingRenderTreeChangesMinimizingRepaintsandReflowsCachingLayoutInformationTakeElementsOutoftheFlowforAnimationsIEand:hoverEventDelegationSummaryAlgorithmsandFlowControlLoopsTypesofLoopsLoopPerformanceFunctionBasedIterationConditionalsifelseVersusswitchOptimizingifelseLookupTablesRecursionCallStackLimitsRecursionPatternsIterationMemoizationSummaryStringsandRegularExpressionsStringConcatenationPlus()andPlusEquals(=)OperatorsArrayJoiningStringprototypeconcatRegularExpressionOptimizationHowRegularExpressionsWorkUnderstandingBacktrackingRunawayBacktrackingANoteonBenchmarkingMoreWaystoImproveRegularExpressionEfficiencyWhenNottoUseRegularExpressionsStringTrimmingTrimmingwithRegularExpressionsviii|TableofContentsTrimmingWithoutRegularExpressionsAHybridSolutionSummaryResponsiveInterfacesTheBrowserUIThreadBrowserLimitsHowLongIsTooLongYieldingwithTimersTimerBasicsTimerPrecisionArrayProcessingwithTimersSplittingUpTasksTimedCodeTimersandPerformanceWebWorkersWorkerEnvironmentWorkerCommunicationLoadingExternalFilesPracticalUsesSummaryAjaxDataTransmissionRequestingDataSendingDataDataFormatsXMLJSONHTMLCustomFormattingDataFormatConclusionsAjaxPerformanceGuidelinesCacheDataKnowtheLimitationsofYourAjaxLibrarySummaryProgrammingPracticesAvoidDoubleEvaluationUseObjectArrayLiteralsDon’tRepeatWorkLazyLoadingConditionalAdvanceLoadingTableofContents|ixUsetheFastPartsBitwiseOperatorsNativeMethodsSummaryBuildingandDeployingHighPerformanceJavaScriptApplicationsApacheAntCombiningJavaScriptFilesPreprocessingJavaScriptFilesJavaScriptMinificationBuildtimeVersusRuntimeBuildProcessesJavaScriptCompressionCachingJavaScriptFilesWorkingAroundCachingIssuesUsingaContentDeliveryNetworkDeployingJavaScriptResourcesAgileJavaScriptBuildProcessSummaryToolsJavaScriptProfilingYUIProfilerAnonymousFunctionsFirebugConsolePanelProfilerConsoleAPINetPanelInternetExplorerDeveloperToolsSafariWebInspectorProfilesPanelResourcesPanelChromeDeveloperToolsScriptBlockingPageSpeedFiddlerYSlowdynaTraceAjaxEditionSummaryIndexx|TableofContentsPrefaceWhenJavaScriptwasfirstintroducedaspartofNetscapeNavigatorin,performancewasn’tthatimportantTheInternetwasinitsinfancyanditwas,inallways,slowFromdialupconnectionstounderpoweredhomecomputers,surfingtheWebwasmoreoftenalessoninpatiencethananythingelseUsersexpectedtowaitforwebpagestoload,andwhenthepagesuccessfullyloaded,itwasacauseforcelebrationJavaScript’soriginalgoalwastoimprovetheuserexperienceofwebpagesInsteadofgoingbacktotheserverforsimpletaskssuchasformvalidation,JavaScriptallowedembeddingofthisfunctionalitydirectlyinthepageDoingsosavedaratherlongtripbacktotheserverImaginethefrustrationoffillingoutalongform,submittingit,andthenwaiting–secondsjusttogetamessagebackindicatingthatyouhadfilledinasinglefieldincorrectlyJavaScriptcanrightfullybecreditedwithsavingearlyInternetusersalotoftimeTheInternetEvolvesOverthedecadethatfollowed,computersandtheInternetcontinuedtoevolveTostart,bothgotmuchfasterTherapidspeedupofmicroprocessors,theavailabilityofcheapmemory,andtheappearanceoffiberopticconnectionspushedtheInternetintoanewageWithhighspeedconnectionsmoreavailablethanever,webpagesstartedbecomingheavier,embeddingmoreinformationandmultimediaTheWebhadchangedfromafairlyblandlandscapeofinterlinkeddocumentsintoonefilledwithdifferentdesignsandinterfacesEverythingchanged,thatis,exceptJavaScriptWhatpreviouslywasusedtosaveserverroundtripsstartedtobecomemoreubiquitousWheretherewereoncedozensoflinesofJavaScriptcodewerenowhundreds,andeventuallythousandsTheintroductionofInternetExploreranddynamicHTML(theabilitytochangeaspectsofthepagewithoutareload)ensuredthattheamountofJavaScriptonpageswouldonlyincreaseovertimeThelastmajorstepintheevolutionofbrowserswastheintroductionoftheDocumentObjectModel(DOM),aunifiedapproachtodynamicHTMLthatwasadoptedbyInternetExplorer,Netscape,andOperaThiswascloselyfollowedbythexistandardizationofJavaScriptintoECMA,thirdeditionWithallbrowserssupportingtheDOMand(moreorless)thesameversionofJavaScript,awebapplicationplatformwasbornDespitethishugeleapforward,withacommonAPIagainstwhichtowriteJavaScript,theJavaScriptenginesinchargeofexecutingthatcoderemainedmostlyunchangedWhyOptimizationIsNecessaryTheJavaScriptenginesthatsupportedwebpageswithafewdozenlinesofJavaScriptinarethesameonesrunningwebapplicationswiththousandsoflinesofJavaScripttodayInmanyways,thebrowsersfellbehindintheirmanagementofthelanguageandindoingthegroundworksothatJavaScriptcouldsucceedatalargescaleThisbecameevidentwithInternetExplorer,whichwasheraldedforitsstabilityandspeedwhenitwasfirstreleasedbutlaterreviledasahorriblewebapplicationplatformbecauseofitsbugsandslownessInreality,IEhadn’tgottenanysloweritwasjustbeingaskedtodomorethanithadpreviouslyThetypesofearlywebapplicationsbeingcreatedwhenIEwasintroducedinweremuchlighterandusedmuchlessJavaScriptthanthosecreatedinThedifferenceintheamountofJavaScriptcodebecameclearastheIEJavaScriptenginestruggledtokeepupduetoitsstaticgarbagecollectionroutineTheenginelookedforafixednumberofobjectsinmemorytodeterminewhentocollectgarbageEarlierwebapplicationdevelopershadrunintothisthresholdinfrequently,butwithmoreJavaScriptcodecomesmoreobjects,andcomplexwebapplicationsbegantohitthisthresholdquiteoftenTheproblembecameclear:JavaScriptdevelopersandwebapplicationshadevolvedwhiletheJavaScriptengineshadnotAlthoughotherbrowsershadmorelogicalgarbagecollectionroutines,andsomewhatbetterruntimeperformance,moststillusedaJavaScriptinterpretertoexecutecodeCodeinterpretationisinherentlyslowerthancompilationsincethere’satranslationprocessbetweenthecodeandthecomputerinstructionsthatmustberunNomatterhowsmartandoptimizedinterpretersget,theyalwaysincuraperformancepenaltyCompilersarefilledwithallkindsofoptimizationsthatallowdeveloperstowritecodeinwhateverwaytheywantwithoutworryingwhetherit’soptimalThecompilercandetermine,basedonlexicalanalysis,whatthecodeisattemptingtodoandthenoptimizeitbyproducingthefastestrunningmachinecodetocompletethetaskInterpretershavefewsuchoptimizations,whichfrequentlymeansthatcodeisexecutedexactlyasitiswrittenIneffect,JavaScriptforcesthedevelopertoperformtheoptimizationsthatacompilerwouldnormallyhandleinotherlanguagesxii|PrefaceNextGenerationJavaScriptEnginesIn,JavaScriptenginesgottheirfirstbigperformanceboostGoogleintroducedtheirbrandnewbrowsercalledChromeChromewasthefirstbrowserreleasedwithanoptimizingJavaScriptengine,codenamedVTheVJavaScriptengineisajustintime(JIT)compilationengineforJavaScript,whichproducesmachinecodefromJavaScriptcodeandthenexecutesitTheresultingexperienceisblazinglyfastJavaScriptexecutionOtherbrowserssoonfollowedsuitwiththeirownoptimizingJavaScriptenginesSafarifeaturestheSquirrelFishExtreme(alsocalledNitro)JITJavaScriptengine,andFirefoxincludestheTraceMonkeyengine,whichoptimizesfrequentlyexecutedcodepathsWiththesenewerJavaScriptengines,optimizationsarebeingdoneatthecompilerlevel,wheretheyshouldbedoneSomeday,developersmaybecompletelyfreeofworryaboutperformanceoptimizationsintheircodeThatday,however,isstillnotherePerformanceIsStillaConcernDespiteadvancementsincoreJavaScriptexecutiontime,therearestillaspectsofJavaScriptthatthesenewenginesdon’thandleDelayscausedbynetworklatencyandoperationsaffectingtheappearanceofthepageareareasthathaveyettobeadequatelyoptimizedbybrowsersWhilesimpleoptimizationssuchasfunctioninlining,codefolding,andstringconcatenationalgorithmsareeasilyoptimizedincompilers,thedynamicandmultifacetedstructureofwebapplicationsmeansthattheseoptimizationssolveonlypartoftheperformanceproblemThoughnewerJavaScriptengineshavegivenusaglimpseintothefutureofamuchfasterInternet,theperformancelessonsoftodaywillcontinuetoberelevantandimportantfortheforeseeablefutureThetechniquesandapproachestaughtinthisbookaddressmanydifferentaspectsofJavaScript,coveringexecutiontime,downloading,interactionwiththeDOM,pagelifecycle,andmoreOfthesetopicsonlyasmallsubset,thoserelatedtocore(ECMAScript)performance,couldberenderedirrelevantbyadvancesinJavaScriptengines,butthathasyettohappenTheothertopicscovergroundwherefasterJavaScriptengineswon’thelp:DOMinteraction,networklatency,blockingandconcurrentdownloadingofJavaScript,andmoreThesetopicswillnotonlycontinuetoberelevant,butwillbecomeareasoffurtherfocusandresearchaslowlevelJavaScriptexecutiontimecontinuestoimprovePreface|xiiiHowThisBookIsOrganizedThechaptersinthisbookareorganizedbasedonanormalJavaScriptdevelopmentlifecycleThisbegins,inChapter,withthemostoptimalwaystoloadJavaScriptontothepageChapterthroughChapterfocusonspecificprogrammingtechniquestohelpyourJavaScriptcoderunasquicklyaspossibleChapterdiscussesthebestwaystobuildanddeployyourJavaScriptfilestoaproductionenvironment,andChaptercoversperformancetoolsthatcanhelpyouidentifyfurtherissuesoncethecodeisdeployedFiveofthechapterswerewrittenbycontributingauthors:•Chapter,DOMScripting,byStoyanStefanov•Chapter,StringsandRegularExpressions,byStevenLevithan•Chapter,Ajax,byRossHarmes•Chapter,BuildingandDeployingHighPerformanceJavaScriptApplications,byJulienLecomte•Chapter,Tools,byMattSweeneyEachoftheseauthorsisanaccomplishedwebdeveloperwhohasmadeimportantcontributionstothewebdevelopmentcommunityasawholeTheirnamesappearontheopeningpageoftheirrespectivechapterstomoreeasilyidentifytheirworkJavaScriptLoadingChapter,LoadingandExecution,startswiththebasicsofJavaScript:gettingcodeontothepageJavaScriptperformancereallybeginswithgettingthecodeontoapageinthemostefficientwaypossibleThischapterfocusesontheperformanceproblemsassociatedwithloadingJavaScriptcodeandpresentsseveralwaystomitigatetheeffectsCodingTechniqueAlargesourceofperformanceproblemsinJavaScriptispoorlywrittencodethatusesinefficientalgorithmsorutilitiesThefollowingsevenchaptersfocusonidentifyingproblemcodeandpresentingfasteralternativesthataccomplishthesametaskChapter,DataAccess,focusesonhowJavaScriptstoresandaccessesdatawithinascriptWhereyoustoredataisjustasimportantaswhatyoustore,andthischapterexplainshowconceptssuchasthescopechainandprototypechaincanaffectyouroverallscriptperformanceStoyanStefanov,whoiswellversedintheinternalworkingsofawebbrowser,wroteChapter,DOMScriptingStoyanexplainsthatDOMinteractionisslowerthanotherpartsofJavaScriptbecauseofthewayitisimplementedHecoversallaspectsoftheDOM,includingadescriptionofhowrepaintandreflowcanslowdownyourcodexiv|PrefaceChapter,AlgorithmsandFlowControl,explainshowcommonprogrammingparadigmssuchasloopsandrecursioncanworkagainstyouwhenitcomestoruntimeperformanceOptimizationtechniquessuchasmemoizationarediscussed,asarebrowserJavaScriptruntimelimitationsManywebapplicationsperformcomplexstringoperationsinJavaScript,whichiswhystringexpertStevenLevithancoversthetopicinChapter,StringsandRegularExpressionsWebdevelopershavebeenfightingpoorstringhandlingperformanceinbrowsersforyears,andStevenexplainswhysomeoperationsareslowandhowtoworkaroundthemChapter,ResponsiveInterfaces,putsthespotlightfirmlyontheuserexperienceJavaScriptcancausethebrowsertofreezeasitexecutes,leavingusersextremelyfrustratedThischapterdiscussesseveraltechniquestoensurethattheuserinterfaceremainsresponsiveatalltimesInChapter,Ajax,RossHarmesdiscussesthebestwaystoachievefastclientservercommunicationinJavaScriptRosscovershowdifferentdataformatscanaffectAjaxperformanceandwhyXMLHttpRequestisn’talwaysthebestchoiceChapter,ProgrammingPractices,isacollectionofbestpracticesthatareuniquetoJavaScriptprogrammingDeploymentOnceJavaScriptcodeiswrittenandtested,it’stimetomakethechangesavailabletoeveryoneHowever,youshouldn’tjustpushoutyourrawsourcefilesforuseinproductionJulienLecomteshowshowtoimprovetheperformanceofyourJavaScriptduringdeploymentinChapter,BuildingandDeployingHighPerformanceJavaScriptApplicationsJuliendiscussesusingabuildsystemtoautomaticallyminifyfilesandusingHTTPcompressiontodeliverthemtothebrowserTestingWhenallofyourJavaScriptcodeisdeployed,thenextstepistobeginperformancetestingMattSweeneycoverstestingmethodologyandtoolsinChapter,ToolsHediscusseshowtouseJavaScripttomeasureperformanceandalsodescribescommontoolsbothforevaluatingJavaScriptruntimeperformanceandforuncoveringperformanceproblemsthroughHTTPsniffingWhoThisBookIsForThisbookisaimedatwebdeveloperswithanintermediatetoadvancedunderstandingofJavaScriptwhoarelookingtoimprovetheperformanceofwebapplicationinterfacesPreface|xvConventionsUsedinThisBookThefollowingtypographicalconventionsareusedinthisbook:ItalicIndicatesnewterms,URLs,emailaddresses,filenames,andfileextensionsConstantwidthUsedforprogramlistings,aswellaswithinparagraphstorefertoprogramelementssuchasvariableorfunctionnames,databases,datatypes,environmentvariables,statements,andkeywordsConstantwidthboldShowscommandsorothertextthatshouldbetypedliterallybytheuserConstantwidthitalicShowstextthatshouldbereplacedwithusersuppliedvaluesorbyvaluesdeterminedbycontextThisiconsignifiesatip,suggestion,orgeneralnoteThisiconindicatesawarningorcautionUsingCodeExamplesThisbookisheretohelpyougetyourjobdoneIngeneral,youmayusethecodeinthisbookinyourprogramsanddocumentationYoudonotneedtocontactusforpermissionunlessyou’rere

用户评论(1)

0/200
  • tangke1973 2011-07-13 20:12:11

    英文版,不是很好看懂

精彩专题

上传我的资料

每篇奖励 +1积分

资料评分:

/46
仅支持在线阅读

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料