关闭

关闭

关闭

封号提示

内容

首页 高性能JavaScript

高性能JavaScript.pdf

高性能JavaScript

魔域私服
2011-06-14 0人阅读 0 0 0 暂无简介 举报

简介:本文档为《高性能JavaScriptpdf》,可适用于IT/计算机领域

HighPerformanceJavaScriptHighPerformanceJavaScriptNicholasCZakasBeijing•Cambridge•Farnham•Köln•Sebastopol•Taipei•TokyoHighPerformanceJavaScriptbyNicholasCZakasCopyright©Yahoo!,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)

  • tangke1973 英文版,不是很好看懂

    2011-07-13 20:12:11

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

评分:

/46

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料