AbouttheAuthor... xviii
AbouttheTechnicalReviewers ... xix
Introduction ... xx
Chapter1:PrinciplesandMethod ...1
Chapter2:ClientPerformance...13
Chapter3:Caching ...61
Chapter4:IIS7.5 ...123
Chapter5:ASP.NETThreadsandSessions...159
Chapter6:UsingASP.NETtoImplementandManageOptimizationTechniques199
Chapter7:ManagingASP.NETApplicationPolicies ...227
Chapter8:SQLServerRelationalDatabase...259
Chapter9:SQLServerAnalysisServices...337
Chapter10:InfrastructureandOperations...371
Chapter11:PuttingItAllTogether ...399
Glossary...421
ThetimethatIspentworkingatMicrosoftwasanunexpectedlytransformingexperience.Thefirsthalf ofmycareerregularlyputmeandthecompaniesIworkedwithincompetitionwithMicrosoft,andIwas oftensurroundedbyanti-Microsoftstoriesandpropaganda.However,whenIheardabout.NET,I decidedIwantedtoknowmoreandthatthebestwaytodothatwastolearnatthesource.
AsIgotintothetechnologyandthecompany,whatIfoundwasmorethanalittlesurprising.The .NETFramework,theC#language,ASP.NET,andSQLServeraresophisticatedandtechnicallybeautiful achievements.AfterworkingwithJavaforseveralyears,whichalsohasadefiniteelegance,itwas refreshingandempoweringtouseawell–integratedplatform,whereeverything(mostly)worked togetherseamlessly.Atatechnicallevel,IfoundthatIusuallyagreedwiththedecisionsandtradeoffs theplatformdevelopersmade,andthattheresultingsystemhelpedtosubstantiallyimprovemy productivityasadeveloper,aswellasthequalityoftheresultingsoftware.IalsofoundtheMicrosoft engineeringteamstobewonderfullybright,creative,and—perhapsmostsurprisingofalltomeasa formeroutsider—sincerelyinterestedinsolvingcustomerproblems.
Myenthusiasmforthetechnologyhelpedcarrymeintoacustomer–facingpositionasasolutions architectattheMicrosoftTechnologyCenterinSiliconValley.Beingexposedin–depthtocustomer issueswasanothereye–openingexperience.First,Icouldseefirst–handtheremarkablypositiveimpact ofMicrosofttechnologiesonmanypeopleandcompanies.Second,Icouldalsoseetheintense
frustrationandpoorresultsthatsomepeoplewerehaving.Thisbookis,inpart,aresponsetosomeof thosefrustrations.
MyperspectiveisthatASP.NETandSQLServerhavetremendouspotential.However,keyaspects ofthetechnologiesarenotobvious.I’vetalkedwith(andinterviewed)manydevelopersandmanagers whosensethepotentialbutwhohavehadextremedifficultywhenitcomestotheimplementation. Unfortunately,realizingthetechnology’sfullpotentialrequiresmoreup–fronteffortthansome alternativeapproaches;it’sarichenvironment,andtoappreciateitfullyrequiresacertainperspective. Oneofmygoalsforthisbookistohelpremovesomeofthefogthatmaybemaskingtheend–to–end visionofthetechnologyandtohelpyouseethebeautyandthefullpotentialofASP.NETandSQL Server.
AnotherreasonIwrotethisbookisthatIamfrustratedconstantlybyhowslowsomesitesare, andI’mhopingyouwillbeabletousetheinformationheretohelpchangethat.TheWebhasamazing possibilities,wellbeyondeventhefantasticlevelit’sreachedalready—buttheycanberealizedonlyif performanceisgood.Slowsitesareaturn–offforeveryone.
WhoThisBookIsFor
Thefirsttwoandlasttwochaptersinthisbookprovideinformationthatwillbeusefultoallweb developers,regardlessofwhichunderlyingtechnologyyouuse.Themiddlesevenchapterswillinterest intermediatetoadvancedarchitectsanddeveloperswhoaredesigning,buildingormaintainingweb sitesusingASP.NETandSQLServer.ExperiencedwebdeveloperswhohaverecentlymovedfromJavaor PHPto.NETwillalsofindlotsofvaluableandinterestinginformationhere.
Thisbookwillbeusefulfornondeveloperswhohaveatechnicalinterestinwhatmakesawebsite fast.Inparticular,ifyou’reinvolvedwithwebsiteoperations,security,testing,ormanagement,youwill discovermanyoftheprinciplesandissuesthatyourdevelopmentteamsshouldbeaddressing,along withdemonstrationsthathelpdrivethepointshome.
ASP.NETMVC,WindowsAzure,andSQLAzure
AlthoughIfocusinthisbookonASP.NETwebforms,IIS,andSQLServerontheserverside,youcan applymanyofthesamefundamentalarchitecturalprinciplestotheASP.NETMVC,WindowsAzure,and SQLAzureplatforms.AlthoughASP.NETMVChasgrownsubstantiallysinceitsintroduction,Microsoft originallybuiltitontopofwebforms,sothefoundationofbothsystemsisthesame.WindowsAzurefor webapplicationsusesIISrunninginvirtualmachines,andSQLAzureisaslightlytrimmed–down, multi–tenantversionofSQLServer.Onceyouunderstandthekeyprinciples,youwillbeabletoapply themregardlessoftheplatformorlanguage.
ContactingtheAuthor
Youcanreachmeatrick@12titans.net.Pleasevisitmywebsiteatwww.12titans.net. Iwouldlovetohearaboutyourexperienceswiththeultra–fastapproach.
Techniquestoimproveperformanceandscalabilityareconstantlyevolving,alongwiththe underlyingtechnology.IamveryinterestedinhearingaboutanytechniquesIhaven’tcoveredherethat youfindtobeeffective.
Pleaseletmeknowifyoufindanyerrorsinthetextorthecodesamples,ortweaksthatcanmake themevenbetter.
Acknowledgments
ForthefirsteditionIwouldliketothankEwanBuckinghamforhisearlysupportandencouragement; MatthewMoodieforhelpwithoverallstructureandflow;SimonTaylorandPhildeJouxfortechnical reviews;AnitaCastroforprojectmanagement;andKimWimpsettforcopyediting.
Principles and Method
Modernlarge-scalewebsitesareamazinglycomplexfeatsofengineering.Partlyasaresultofthis,many sitesrunintosignificantperformanceandscalabilityproblemsastheygrow.Infact,it’snotunusualfor largesitestobereengineeredalmostfromscratchatsomepointinordertohandletheirgrowth. Fortunately,consistentlyfollowingafewbasicprinciplescanmakesitesfasterwhilethey’restillsmall, whileminimizingtheproblemsyouwillencounterastheygrow.
Thisbookwillexplorethoseprinciplesandshowhowandwhyyoushouldapplythem.
I’mbasingtheideaspresentedhereonmyworkdevelopingnetwork-orientedsoftwareoverthepast 30+years.IstartedworkingwiththeInternetin1974andwithUnixandCin1979andlatermovedto C++andthenJavaandC#.IlearnedaboutASP.NETandSQLServerindepthwhileworkingatMicrosoft, whereIhelpedarchitectanddevelopalarge-scalewebsiteforMSNTV.Ipolishedthatknowledgeover thenextfewyearswhileIwasanarchitectattheMicrosoftTechnologyCenter(MTC)inSiliconValley. Duringthattime,Ihelpedruntwo-tothree-dayarchitecturaldesignsessionsonceortwiceeachweek forsomeofMicrosoft’slargestandmostsophisticatedcustomers.OtherMTCarchitectsandIwould worktofirstunderstandcustomerissuesandproblemsandthenhelparchitectsolutionsthatwould addressthem.
Itdidn’ttakelongbeforeIdiscoveredthatalotofpeoplehadthesamequestions,manyofwhich werefocusedaroundperformanceandscalability.Forexample:
• “HowcanwemakeourHTMLdisplayfaster?”(Chapter2) • “What’sthebestwaytodocaching?”(Chapter3)
• “HowcanweuseIIStomakeoursitefaster?”(Chapter4) • “Howshouldwehandlesessionstate?”(Chapter5)
• “HowcanweimproveourASP.NETcode?”(Chapters5to7) • “Whyisourdatabaseslow?”(Chapters8and9)
• “Howcanweoptimizeourinfrastructureandoperations?”(Chapter10) • “Howdoweputthepiecestogether?”(Chapter11)
OneaspectoftheapproachI’vetakenistolookatawebsitenotjustasanapplicationrunningona remoteserverbutratherasadistributedcollectionofcomponentsthatneedtoworkwelltogetherasa system.
Inthischapter,I’llstartwithadescriptionofperformanceandscalability,alongwithwhatImean byultra-fastandultra-scalable.ThenI’llpresentahigh-leveloverviewoftheend-to-endprocessthat’s involvedingeneratingawebpage,andI’lldescribethecoreprinciplesuponwhichIbasethisapproach toperformance.I’llconcludewithadescriptionoftheenvironmentandtoolsthatIusedindeveloping theexamplesthatIpresentlaterinthebook.
TheDifferenceBetweenPerformanceandScalability
Wheneversomeonetellsmethattheywanttheirsystemtobefast,thefirstquestionIaskis,“Whatdo youmeanbyfast?”Atypicalanswermightbe“Itneedstosupportthousandsofusers.”Asitecanbeslow andstillsupportthousandsofusers.
Scalabilityandperformancearedistinctlydifferent.Inthecontextofthisbook,whenItalkabout improvingasite’sperformance,whatImeanisdecreasingthetimeittakesforaparticularpagetoload orforaparticularuser-visibleactiontocomplete.Whatasingleuserseeswhilesittingattheircomputer is“performance.”
Scalability,ontheotherhand,hastodowithhowmanyusersasitecansupport.Ascalablesiteis onethatcaneasilysupportadditionalusersbyaddingmorehardwareandnetworkbandwidth(no significantsoftwarechanges),withlittleornodifferenceinoverallperformance.Ifaddingmoreusers causesthesitetoslowdownsignificantlyandaddingmorehardwareorbandwidthwon’tsolvethe problem,thenthesitehasreacheditsscalabilitythreshold.Oneofthegoalsindesigningforscalabilityis toincreasethatthreshold;itwillnevergoaway.
Why
Ultra-fast
and
Ultra-scalable
?
Speedandscalabilityshouldapplytomorethanjustyourwebservers.Manyaspectsofweb
developmentcanandshouldbefastandscalable.Allofyourcodeshouldbefast,whetheritrunsatthe client,inthewebtier,orinthedatatier.Allofyourpagesshouldbefast,notjustafewofthem.Onthe developmentside,beingfastmeansbeingagile:fastchangesandfixes,anddeployments.
Adefinitesynergyhappenswhenyouapplyspeedandscalabilitydeeplyinaproject.Notonlywill yourcustomersandusersbehappier,butengineerstoowillbehappierandwillfeelmorechallenged. Surprisingly,lesshardwareisoftenrequired,andqualityassuranceandoperationsteamscanoftenbe smaller.That’swhatImeanbyultra-fastandultra-scalable(whichIwilloftenrefertoasjustultra-fast forshort,eventhoughscalabilityisalwaysimplied).
Theultra-fastapproachisverydifferentfromanimpulsive,“do-it-now”typeofprogramming.The architecturalproblemsthatinevitablyarisewhenyoudon’tapproachdevelopmentinamethodicalway tendtosignificantlyoffsetwhatevershort-termbenefitsyoumightrealizefromtakingshortcuts.Most large-scalesoftwaredevelopmentprojectsaremarathons,notsprints;advanceplanningand
preparationpayhugelong-termbenefits.
Table1-1.GoalsoftheUltra-fastandUltra-scalableApproach
Component
Ultra-fast and Ultra-scalable Goals
Pages Everypageisscalableandfastunderload.
Tiers Alltiersarescalableandfastunderload.
Agility Youcanrespondquicklytochangingbusinessneeds,andyoucanreadilymaintain performanceandscalabilityintheeventofchanges.
Maintainability Youcanquicklyfindandfixperformance-relatedbugs.
Operations Youcanquicklydeployandgrowyoursites.Capacityplanningisstraightforwardand reliable.
Hardware Yourserversarewellutilizedunderload;fewermachinesarerequired.
Buildingafastandscalablewebsitehassomehigh-levelsimilaritiestobuildingaracecar.Youneed toengineeranddesignthecoreperformanceaspectsfromthebeginninginorderforthemtobe
effective.Inracing,youneedtodecidewhatclassorleagueyouwanttoracein.IsitgoingtobeFormula One,stockcar,rallying,dragster,ormaybejustkart?Ifyoubuildacarforkart,notonlywillyoube unabletocompeteinFormulaOne,butyouwillhavetothrowthewholedesignawayandstartagainif youdecideyouwanttochangetoanewclass.Withwebsites,buildingasiteforjustyourselfandafew friendsisofcoursecompletelydifferentfrombuildingeBayorYahoo.Adesignthatworksforonewould becompletelyinappropriatefortheother.
Atop-endracecardoesn’tjustgofast.Youcanalsodothingslikechangeitswheelsquickly,fillit withfuelquickly,andevenquicklyswapouttheengineforanewone.Inthatway,racecarsarefastin multipledimensions.Yourwebsiteshouldalsobefastinmultipledimensions.
Inthesamewaythatit’sabadideatodesignaracecartogofastwithoutconsideringsafety,itis alsonotagoodideatodesignahigh-performancewebsitewithoutkeepingsecurityinmind.Inthe chaptersthatfollow,Iwillthereforemakeanoccasionalbriefdiversionintosecurityinareaswherethere issignificantoverlapwithperformance,suchaswithcookiesinChapter3.
Optimization
Asmanyindustryexpertshaverightlypointedout,optimizationcanbeadeadlytrapandtime-waster. Thekeytobuildinghigh-performancewebsitesisengineeringthemsothatoptimizationisnotrequired togetdecentresults.However,aswithracing,ifyouwanttocompetewiththebest,thenyouneedto integratemeasuring,adjusting,tuning,tweaking,andinnovatingintoyourdevelopmentprocess. There’salwayssomethingyoucandobetter,providedyouhavethetime,money,andmotivationto doso.
Therealtrickisknowingwheretolookforperformanceandscalabilityproblemsandwhatkindsof changesarelikelytohavethebiggestimpact.Comparingtheweightofwheellugstooneanotheris probablyawasteoftime,butgettingthefuelmixturejustrightcanwintherace.Improvingthe
Idon’tmeanthatsmallthingsaren’timportant.Infact,manysmallproblemscanquicklyaddupto beabigproblem.However,whenyou’reprioritizingtasksandallocatingtimetothem,besuretofocus onthehigh-impacttasksfirst.Puttingahighpolishonaracecarisniceandmighthelpitgoalittle faster,butifthetransmissionisnogood,youshouldfocusyoureffortstherefirst.Polishingsome internalAPIjusthowyouwantitmightbenice,buteliminatinground-tripsshouldbeamuchhigher priority.
Process
Ultra-fastisastateofmind—aprocess.Itbeginswiththearchitectureandthedesign,anditflowsinto allaspectsofthesystem,fromdevelopmenttotestingtodeployment,maintenance,upgrades,and optimization.However,aswithbuildingaracecaroranyothercomplexproject,thereisusuallyasense ofurgencyandadesiretogetsomethingdonequicklythat’s“goodenough.”Understandingwherethe bigimpactpointsareisacriticalpartofbeingabletodothateffectively,whilestillmeetingyour businessgoals.TheapproachI’vetakeninthisbookistofocusonthethingsyoushoulddo,ratherthan toexploreeverythingthatyoucoulddo.Thegoalistohelpyoufocusonhigh-impactareasandtoavoid gettinglostintheweedsintheprocess.
I’veworkedwithmanysoftwareteamsthathavehaddifficultygettingmanagementapprovalto workonperformance.Oftenthesesameteamsrunintoperformancecrises,andthosecrisessometimes leadtoredesigningtheirsitesfromscratch.Managementtendstofocusinevitablyonfeatures,aslongas performanceis“goodenough.”Theproblemisthatperformanceisonlygoodenoughuntilitisn’t—and that’swhenacrisishappens.Inmyexperience,youcanoftenavoidthisslipperyslopebynotselling performancetomanagementasafeature.It’snotafeature,anymorethansecurityorqualityare features.Performanceandtheotheraspectsoftheultra-fastapproachareanintegralpartofthe application;theypermeateeveryfeature.Ifyou’rebuildingaracecar,makingitgofastisn’tanextra featurethatyoucanaddattheend;itispartofthearchitecture,andyoubuilditintoeverycomponent andeveryprocedure.
There’snomagichere.Thesearethekeystomakingthiswork: • Developingadeepunderstandingofthefullend-to-endsystem • Buildingasolidarchitecture
• Focusingeffortonhigh-impactareas,andknowingwhat’ssafetoignoreordefer • Understandingthatalittleextraup-fronteffortwillhavebigbenefitsinthelong
term
• Usingtherightsoftwaredevelopmentprocessandtools
TheFullExperience
Performanceshouldencompassthefulluserexperience.Forexample,thetimetoloadthefullpageis onlyoneaspectoftheoveralluserexperience;perceivedperformanceisevenmoreimportant.Ifthe usefulcontentappears“instantly”andthensomeadsshowuptensecondslater,mostuserswon’t complain,andmanywon’tevennotice.However,ifyoudisplaythepageintheoppositeorder,withthe slowadsfirstandthecontentafterward,youmightrisklosingmanyofyourusers,eventhoughthetotal pageloadtimeisthesame.
Websitesthatonepersonbuildsandmaintainscanbenefitfromthisapproachasmuchaslarger websitescan(imagineakartracerwithsomeFormulaOneparts).Afastsitewillattractmoretrafficand morereturnvisitorsthanaslowone.Youmightbeabletogetalongwithasmallerserveroraless expensivehostingplan.Yourusersmightvisitmorepages.
Asanexampleofwhat’spossiblewithASP.NETandSQLServerwhenyoufocusonarchitectureand performance,onesoftwaredeveloperbyhimselfbuiltthesitepof.com,andin2009,itwasoneofthe highest-trafficsitesinCanada.Thesiteservesmorethan45millionvisitorspermonth,with1.2billion pageviewspermonth,or500to600pagespersecond.Yetitonlyusesthreeload-balancedwebservers, withdualquad-coreCPUsand8GBRAM,plusafewdatabaseservers,alongwithacontentdistribution network(CDN).TheCPUsonthewebserversaverage30percentbusy.Idon’tknowmanydetailsabout theinternalsofthatsite,butafterlookingattheHTMLitgenerates,I’mconfidentthatyoucouldusethe techniquesI’mprovidinginthisbooktoproduceacomparablesitethat’sevenfaster.
Unfortunately,there’snofreelunch:buildinganultra-fastsitedoestakemorethoughtand planningthanaquick-and-dirtyapproach.Italsotakesmoredevelopmenteffort,althoughusuallyonly inthebeginning.Overthelongrun,maintenanceanddevelopmentcostscanactuallybesignificantly less,andyoushouldbeabletoavoidanycostlyground-uprewrites.Intheend,Ihopeyou’llagreethat thebenefitsareworththeeffort.
End-to-EndWebPageProcessing
AcommonwaytothinkabouttheWebisthatthereisabrowserononeendofanetworkconnection andawebserverwithadatabaseontheotherend,asinFigure1-1.
Figure1-1.Simplifiedwebarchitecturemodel
Figure1-2.Webarchitecturecomponentsthatcanimpactperformance
Inthefollowinglist,I’vesummarizedtheprocessofloadingawebpage.Eachofthesestepsoffers opportunitiesforoptimizationthatI’lldiscussindetaillaterinthebook:
1. First,thebrowserlooksinitslocalcachetoseewhetheritalreadyhasacopyof thepage.SeeChapter2.
2. Ifthepageisn’tinthelocalcache,thenthebrowserlooksuptheIPaddressof theweborproxyserverusingDNS.Thebrowserandtheoperatingsystem haveeachhaveseparateDNScachestostoretheresultsofpreviousqueries.If theaddressisn’talreadyknownorifthecacheentryhastimedout,thena nearbyDNSserverisusuallyconsultednext(it’softeninalocalrouter,for example).SeeChapter10.
3. Next,thebrowseropensanetworkconnectiontotheweborproxyserver. Proxyserverscanbeeithervisibleortransparent.Avisibleproxyisonethatthe user’sbrowseroroperatingsystemisawareof.Theyaresometimesusedat largecompanies,forexample,tohelpimprovewebperformancefortheir employeesorsometimesforsecurityorfilteringpurposes.Atransparentproxy interceptsalloutgoingTCPconnectionsonport80(HTTP),regardlessoflocal clientsettings.Ifthelocalproxydoesn’thavethedesiredcontent,thenthe HTTPrequestisforwardedtothetargetwebserver.SeeChapters2and3. 4. SomeISPsalsouseproxiestohelpimproveperformancefortheircustomers
andtoreducethebandwidththeyuse.Aswiththelocalproxy,ifthecontent isn’tavailableintheISPproxycache,thentherequestisforwardedalong.See Chapter3.
5. Thenextstopisawebserveratthedestinationsite.Alargesitewillhavea numberofload-balancedwebservers,anyofwhichwillbeabletoacceptand processincomingrequests.Eachmachinewillhaveitsownlocaldiskand separatecachesattheoperatingsystemdriverlevel(http.sys),inInternet InformationServices(IIS),andinASP.NET.SeeChapters3through7. 6. Iftherequestedpageneedsdatafromthedatabase,thenthewebserverwill
openaconnectiontooneormoredatabaseservers.Itcanthenissuequeries forthedataitneeds.ThedatamightresideinRAMcacheinthedatabase,orit mightneedtobereadinfromdisk.SeeChapters8and9.
7. Whenthewebserverhasthedataitneeds,itdynamicallycreatesthe requestedpageandsendsitbacktotheuser.Iftheresultshaveappropriate HTTPresponseheaders,theycanbecachedinmultiplelocations.See Chapters3and4.
OverviewofPrinciples
Thefirstandmostimportantruleofbuildingahigh-performancesiteisthatperformancestartswiththe applicationitself.Ifyouhaveapagewithaloopcountingtoagazillion,forexample,nothingI’m describingwillhelp.
PerformancePrinciples
Withtheassumptionofasoundimplementation,thefollowingaresomehigh-impactcorearchitectural principlesforperformanceandscalability:
• Focusonperceivedperformance.Usersarehappieriftheyquicklyseearesponse aftertheyclick.It’sevenbetterifwhattheyseefirstistheinformationthey’re mostinterestedin.SeeChapter2.
• Reduceroundtrips.Everyroundtripisexpensive,whetherit’sbetweentheclient andthewebserverorbetweenthewebserverandthedatabase.“Chattiness”is oneofthemostcommonkillersofgoodsiteperformance.Youcaneliminatethese typesofroundtripsbycaching,combiningrequests(batching),combiningsource filesordata,combiningresponses(multipleresultsets),workingwithsetsofdata, andothersimilartechniques.SeeChapters2through8.
• Cacheatalltiers.Cachingisimportantatmoststepsofthepagerequestprocess. Youshouldleveragethebrowser’scache,cookies,on-pagedata(hiddenfieldsor
ViewState),proxies,theWindowskernelcache(http.sys),theIIScache,the ASP.NETapplicationcache,pageandfragmentoutputcaching,theASP.NET cacheobject,server-sideper-requestcaching,databasedependencycaching, distributedcaching,andcachinginRAMatthedatabase.SeeChapters3and8.
• OptimizediskI/Omanagement.Disksarephysicaldevices;theyhaveplatters thatspinandread/writeheadsthatmovebackandforth.Rotationandhead movement(diskseeks)taketime.DisksworkmuchfasterwhenyoumanageI/O toavoidexcessiveseeks.ThedifferenceinperformancebetweensequentialI/O andrandomI/Ocaneasilybe40to1ormore.Thisisparticularlyimportanton databaseservers,wherethedatabaselogiswrittensequentially.Properhardware selectionandconfigurationplaysabigrolehere,too,includingchoosingthetype andnumberofdrives,usingthebestRAIDlevel,usingtherightnumberoflogical drivesorLUNs,andsoon.SolidStateDisks(SSDs)havenomovingparts,andcan bemuchfasterforcertainI/Opatterns.SeeChapters8and10.
SecondaryTechniques
Youcanoftenapplyanumberofsecondarytechniqueseasilyandquicklythatwillhelpimprovesystem-levelperformanceandscalability.Aswithmostofthetechniquesdescribedhere,it’seasiertoapply themeffectivelywhenyoudesignthemintoyourwebsitefromthebeginning.Aswithsecurityand qualityrequirements,thelaterinthedevelopmentprocessthatyouaddressperformanceandscalability requirements,themoredifficulttheproblemstendtobe.I’vesummarizedafewexamplesofthese techniquesinthefollowinglist:
• Understandbehavior.Byunderstandingthewaythatthebrowserloadsaweb page,youcanoptimizeHTMLandHTTPtoreducedownloadtimeandimprove bothtotalrenderingspeedandperceivedspeed.SeeChapter2.
• AvoidfullpageloadsbyusingAjaxandplainJavaScript.Youcanuseclient-side fieldvalidationandothertypesofrequestgatingwithJavaScripttocompletely avoidsomepagerequests.YoucanuseAjaxtorequestsmallamountsofdatathat canbedynamicallyinsertedintothepageorintoarichuserinterface.See Chapter2.
• Avoidsynchronousdatabasewritesoneveryrequest.Heavydatabasewritesarea commoncauseofscalabilityproblems.Incorrectuseofsessionstateisafrequent sourceofproblemsinthisarea,sinceithastobebothreadandwritten(and deserializedandreserialized)witheveryrequest.Youmaybeabletousecookies toreduceoreliminatetheneedforserver-sidesessionstatestorage.SeeChapters 5and8.
• UnderstandhowSQLServermanagesmemory.Forexample,whenaT-SQL commandmodifiesadatabase,theserverdoesasynchronous(andsequential) writetothedatabaselog.Onlyafterthewritehasfinishedwilltheserverreturnto therequestor.Themodifieddatapagesarestillinmemory.Theywillstaythere untilSQLServerneedsthememoryforotherrequests;theywillbewrittentothe datafilebythebackgroundlazywriterthread.ThismeansthatSQLServercan processsubsequentreadrequestsforthesamedataquicklyfromcache.Italso meansthatthespeedofthelogdiskhasadirectimpactonyourdatabase’swrite throughput.SeeChapter8.
• Effectiveuseofpartitioningatthedatatier.Oneofthekeystoaddressing
databasescalabilityistopartitionyourdata.Youmightreplicateread-onlydatato agroupofload-balancedserversrunningSQLExpress,oryoumightpartition writabledataamongseveralseversbasedonaparticularkey.Youmightsplitup datainasinglelargetableintomultiplepartitionstoavoidperformanceproblems whenthedataisprunedorarchived.SeeChapter8.
Iwilldiscusstheseandothersimilartechniquesatlengthinthechaptersahead.
Whatthisbookisnotaboutislow-levelcodeoptimization;myfocushereismostlyonthehigh-impactaspectsofyourapplicationarchitectureanddevelopmentprocess.
EnvironmentandToolsUsedinThisBook
Althoughcross-browsercompatibilityisimportant,inkeepingwiththepointImadeearlierabout focusingonthehigh-impactaspectsofyoursystem,I’vefoundthatfocusingdevelopmentandtuning effortsonthebrowsersthatcomprisethetop90percentorsoinusewillbringmostoftherestforfree. Youshouldbeabletomanagewhateverquirkinessmightbeleftafterwardonanexceptionbasis,unless you’rebuildingasitespecificallyorientedtowardoneoftheminoritybrowsers.
Ialsodon’tconsiderthecaseofbrowserswithoutJavaScriptorcookiesenabledtoberealistic anymore.Withoutthosefeatures,theWebbecomesafairlybarrenplace,soIthinkofthemasbeinga givenforrealusers;searchenginesandotherbotsareanentirelydifferentstory,ofcourse.
AsofApril2012,themostpopularbrowsersaccordingtoNetApplicationswereInternetExplorer with54percent,Firefoxwith21percent,andChromewith19percent.Theremaining6percentwassplit betweenSafari,Opera,andothers.
SoftwareToolsandVersions
ThespecifictoolsthatI’veusedforthecodeexamplesandfiguresarelistedinTable1-2,includinga roughindicationofcost.Asingle$indicatesapriceunderUS$100,$$isbetween$100and$1,000,and $$$ismorethan$1,000.
Table1-2.SoftwareToolsandVersions
Software Version
Cost
AdobePhotoshop CS5 $$
Software Version
Cost
ExpressionWeb 4.0.1303.0SP2 $$
FiddlerWebDebugger 2.3.9 Freedownload
Firebug 1.10 Freedownload(Firefoxplug-in)
Firefox11.0 Freedownload
InternetExplorer 8and9 Freedownload
LogParser 2.2 Freedownload
.NETFramework 4.5 Freedownload
Office 2010Ultimate $$
Silverlight5 Freedownload
SQLServer 2012RC0Developer,
StandardandEnterprise $ $$$
SQLServerDataTools April2012 Freedownload(VSplug-in)
SQLServerFeaturePack October2008 Freedownload
SystemCenterOperationsManager 2012RC $$
VisualStudio 2010PremiumSP1,
11DeveloperPreview&Beta $$$
WindowsServer 2008R2Standard $$
Windows 7Professionalx64 $$
Wireshark1.6.4 Freedownload
YSlow 3.0.4 Freedownload(Firefoxplug-in)
Terminology
Seetheglossaryfordefinitionsofbusinessintelligence(BI)-specificterminology.
TypographicConventions
Iamusingthefollowingtypographicconventions:
• Italics:Termdefinitionsandemphasis • Bold:Textasyouwouldseeitonthescreen
• Monospace:Code,URLs,filenames,andothertextasyouwouldtypeit
Author’sWebSite
Mywebsiteathttp://www.12titans.net/hasonlineversionsofmanyofthewebpagesusedassamples ordemonstrations,alongwithcodedownloadsandlinkstorelatedresources.
Summary
Inthischapter,Icoveredthefollowing:
• Performancerelatestohowquicklysomethinghappensfromyourenduser’s perspective,whilescalabilityinvolveshowmanyusersyoursitecansupportand howeasilyitcansupportmore.
• Ultra-fastandUltra-scalableincludemorethanjusttheperformanceofyourweb server.Youshouldapplyspeedandscalabilityprinciplesatalltiersinyour architecture.Inaddition,yourdevelopmentprocessshouldbeagile,withthe abilitytochangeanddeployquickly.
• Processingarequestforawebpageinvolvesanumberofdiscretesteps,manyof whichpresentopportunitiesforperformanceimprovements.
• Youshouldapplyseveralkeyperformanceandscalabilityprinciplesthroughout yoursite:focusonperceivedperformance,reduceroundtrips,cacheatalltiers, minimizeblockingcalls,andoptimizediskI/Omanagement.
Client Performance
Theprocessofdisplayingawebpageinvolvesdistributedcomputing.AbrowserontheclientPC requestsandparsestheHTML,JavaScript,CSS,images,andotherobjectsonapage,whileoneormore serversgenerateanddeliverdynamicandstaticcontent.Buildingafastsystemthereforerequiresa capacityforspeedinboththebrowserandtheserver,aswellasinthenetworkandothercomponentsin between.Onewaytothinkaboutthisisbyviewingtheserverasreallysendingoneormoreprogramsto thebrowserintheformofHTML(whichisafterall,HypertextMarkupLanguage)andJavaScript.The browserthenhastoparseandexecutethoseprogramsandrendertheresultstothescreen.
Forexistingsites,I’vefoundthatlargeruser-visibleperformanceimprovementscanoftenbe obtainedbyoptimizingtheoutputofyourwebsitesothatitrunsfasterontheclientratherthanby makingyourserver-sidecoderunfaster.Itisthereforeagoodplacetostartontheroadtobuildingan ultra-fastsite.
Particularlyonthebrowsersideoftheperformanceequation,manysmallimprovementscan quicklyadduptoalargeone.Slowsitesareoftentheresultofthe“deathby1,000cuts”syndrome.Afew extracharactershereortheredon’tmatter.However,manysmalltransgressionscanquicklyaddupto makethedifferencebetweenaslowsiteandafastone,orbetweenafastsiteandanultra-fastone. Anotherwaytothinkaboutthisisthatit’softenaloteasiertosaveahandfulofbytesin100placesthan 100bytesinahandfulofplaces.
Imaginebuildingahouse.Alittleneglecthereortherewon’tcompromisethequalityofthefinal product.However,iftheattitudebecomespervasive,itdoesn’ttakelongbeforethewholestructure suffersasaresult.Infact,atsomepoint,repairsareimpossible,andyouhavetoteardownthehouse andbuildagainfromscratchtogetitright.Asimilarthinghappenswithmanyaspectsofsoftware, includingperformanceandscalability.
Inthischapter,Iwillcoverthefollowing: • Browserpageprocessing
• Browsercaching • Networkoptimizations
• UsingJavaScripttogatepagerequests • UsingJavaScripttoreduceHTMLsize • Uploadingless
• OptimizingCSS
• Usingimagespritesandclustering
• LeveragingdynamicHTMLandJavaScript(Ajax) • Improvinglayoutandrenderingspeed
• Precaching
• UsingCSSlayoutwithouttables • OptimizingJavaScriptperformance
Theexamplefilesforthischapterareavailableonlineatwww.12titans.netandinthedownload that’savailablefromwww.apress.com.
BrowserPageProcessing
Whenabrowserloadsapage,it’snotperformingabatchprocess.Usersdon’tclosetheireyesafterthey enteraURLandopenthemagainwhenthebrowserhasfinishedloadingthepage.Browsersdowhat theycantooverlapactivityonmultiplenetworkconnectionswithpageparsingandrenderingtothe screen.Thestepsthatbrowsersfollowareoftenextremelyvisibletousersandcanhaveasignificant impactonbothperceivedperformanceandtotalpageloadtime.
NetworkConnectionsandtheInitialHTTPRequest
Toretrieveawebpage,browsersstartwithaURL.ThebrowserdeterminestheIPaddressoftheserver usingDNS.Then,usingHTTPoverTCP,thebrowserconnectstotheserverandrequeststhecontent associatedwiththeURL.Thebrowserparsestheresponseandrendersittothescreeninparallelwith theongoingnetworkactivity,queuingandrequestingcontentfromotherURLsinparallelasitgoes.
Ratherthangettingtoosidetrackedwiththevariationsfromonebrowsertoanother,myfocushere willmostlybeonInternetExplorer9(IE9,orjustIE).Otherbrowsersworksimilarly,althoughthereare definitedifferencesfromoneimplementationtoanother.WithFirefox,userscansetparametersthat changesomeofthedetailsofhowitprocessespages,sothepageloadexperiencemaynotbe100 percentidenticalfromoneusertoanother,evenwhenthey’reusingthesamebrowser.
Figure2-1.TypicalTCPprotocolexchangewhenrequestingawebpage,witheachboxrepresentinga packet
TheclientbrowseraskstheservertoopenaconnectionbysendingaTCPSYNpacket.Theserver respondsbyacknowledgingtheSYNusingaSYNACK,andtheclientrespondswithanACK.Afterthis three-wayhandshake,theconnectionisopen.
ThebrowserthensendsanHTTPGET,whichincludestherequestedURL,cookies,andotherdetails. Uponreceipt,theserverACKsthatpacket,andduringthetimemarkedasAinFigure2-1,itgeneratesits responsetotheclient’srequest.
Youcanseethattheresponsetothebrowser’srequestdoesn’tarriveallatonce.Therearegapsof timebetweenwhentheclientsendsapacketandwhentheserverresponds,aswellasinbetween successivepackets.
Horizontalzones,suchasareaAinFigure2-1wheretherearenoboxescontainingpackets,indicate thatthenetworkisidleduringthosetimes.Downloadingmultipleresourcesoverparallelconnections canhelpminimizethatidletimeandtherebyminimizetotalpageloadtime.
Themaximumpacketsizevariesfrom500to1,500bytes,dependingonthenetworkmaximum transmissionunit(MTU).ThefirstdatapacketfromtheserverincludestheHTTPresponseheader, usuallyalongwithsomeHTML,dependingonthesizeoftheheader.BecauseofthewaythattheTCP networkprotocolworks(afeaturecalledslowstart),therecanbearelativelylongdelaybetweenthetime whenthefirstdatapacketarrivesandwhenthenextonedoes,whilethenetworkconnectionrampsup tofullspeed.
TheSYNandSYNACKpackets,alongwithTCPslow-start,combinetomakeopeninganetwork connectionarelativelytime-consumingprocess.Thisisthereforesomethingthatwewouldliketoavoid doingtoomuch.
PageParsingandNewResourceRequests
WhileIEiswaitingforthenextpacketofdata,itparseswhatitalreadyhasandlooksforanyresource URLsthatitmightbeabletodownloadinparallel.Itwillopenasmanyassixconnectionstoeachserver.
Thetimelineshownhere(capturedusingIE’sF12developertools)illustrateshowIEhandlesapage wherean<img>tagislocatedafterofabunchoftext(seefile01.htm).
Thehorizontalaxisistime,andeachrowcorrespondstoadifferentrequestmadebythebrowser. ThefirstrowshowsthetimetakentoreadtheHTMLpage.Thesectionontheleftofthehorizontalbaris thetimefromwhenIEinitiallycreatedtherequesttowhenitsendstherequest.Themiddlesectionis thetimetakentoopenaTCPconnection(ifrequired),sendtheinitialHTTPGETrequest,andreceivethe firstpacketoftheHTTPresponse.Thesectionontherightisthetimetakenfortherestoftheresponse toarrive.
Thesecondrowshowstheretrievaloftheimage.Sincetheimageissmall,alloftheimagedatais includedwiththeHTTPresponseheadersinthesamepacket.
Thenexttimelineshowswhathappenswhenthe<img>tagislocatedclosetothebeginningofthe filesothatit’sinthefirstpacketofdatareceivedbyIE(seefile02.htm):
Thefirstrowisroughlythesame.However,therequestfortheimagestartsshortlyafterthefirst packetofHTMLarrives.Asaresult,ittakeslesstotaltimetoretrievethepageandtheimage.(The verticalbaristhepointatwhichIEraisedthedocumentreadyevent).
PageResourceOrderandReordering
IEretrievesallresourcesrequestedinthe<head>sectionoftheHTMLbeforeitstartsrenderingthe
<body>.Sincethe<head>sectioncan’tcontainanytagsthatwillcausethebrowsertodrawcontenton thescreen,userswillseenothinguntilithasdownloadedallresourcesinthe<head>section.
WhileIEisblockedwaitingonresourcesforthe<head>section,itusesafeaturecalledlookaheadto downloadresourcesfromthe<body>sectioninparallel.However,lookaheadhaslimitations,soin general,ifyouplacetherequestsinthe<body>sectioninsteadwhenpossible,youcanhelpthebrowser optimizethedownloadingofresourcesinparallel.
Note
TheHTMLspecificationcallsfor
<link>and
<style>tags(forCSS)tobeinthe
<head>section,although
currentbrowsersdon’tenforcethatlimitation.
AsHTMLparsingcontinues,resourcesthatthepagereferences,includingimages,aregenerally queuedforretrievalintheorderIEencountersthem.IE9willrequestanimagenearthetopofthefile beforeotherresourcesfromthesamedomain(IE8mayqueueJavaScriptresourcesbeforeimagesdueto lookahead).Youmaybeabletoimprovethe(apparent)performanceofapagebymanagingobject downloadorder,eitherbyrearrangingyourHTMLorusingout-of-orderloading.Forexample,ifyou havealargeimagebannerorlogoatthetopofyourpage,althoughitmaybeimportantforsite aestheticsorbranding,itmaynotbethefirstthingthatuserswanttosee.However,ifit’satthetopof theHTML,itwillbethefirstthingdownloadedbythebrowser.
YoucanuseJavaScriptandCSStoachieveout-of-orderobjectloading.Forexample,youcanreserve thespaceonthepagewithan<img>tagandrequesttheimageassociatedwiththattagearlierorlaterin thefileusingscript.Thatway,youcancallthescriptaccordingtowhenusersshouldseetheimage. Here’sanexampleoflateloading:
<img id="myimg" width="50" height="50" /> . . .
<script type="text/javascript">
document.getElementById("myimg").src = "myimage.jpg"; </script>
Or,usingjQuery:
<img id="myimg" width="50" height="50" /> . . .
<script type="text/javascript">
$("#myimg").attr("src", "myimage.jpg"); </script>
Note
Asabestpractice,youshouldalwaysspecifythe
widthand
heightforyourimages,usingeither
propertiesorCSS.Doingsohelpsminimizethetimetakenbythebrowsertolayoutthepage,asitdoesnothave
toreflowthecontentafterdeterminingtheimage’struesize.
Forearlyloading:
<script type="text/javascript"> var myimg = new Image(); myimg.src = "myimage.jpg"; </script>
. . .
<img src="myimage.jpg" width="50" height="50" />
AllocateanImageobject,andsetitssrcattributetothedesiredfilename.Thiswillcausethebrowser toqueuetheimagefordownloading.Then,inthe<img>tag,justusethesamefilenameagain.Sincethe browsershouldcachetheimage,itwillbedownloadedonlyonce.
Youshoulduselateloadingforimagesthattheuserwouldn’tconsiderimportantorthatarebelow thefold,wheretheywon’tbeseenrightaway.Youshoulduseearlyloadingforimagesthatare
importanttotheuserandthatareabovethefold.
BrowserCaching
AllcomponentsofURLsexceptthehostnamearecase-sensitive.SincetheWindowsfilesystemandIIS URLhandlingarenot(unlikeUnix/LinuxwithApache),thiscanresultinthebrowserdownloadingthe sameobjectmorethanonceifyoudon’tuseaconsistentcaseforURLsthatrefertothesameobject. BrowserscanonicalizeURIs(removing“..”)andthenuseadirectstringcomparisontodetermine whethertwoURIsrefertothesameobject.Forexample,thefollowingcodewouldcausethebrowserto downloadthesameimagetwice:
<img src="myimage.jpg" width="50" height="50" /> <img src="myimage.JPG" width="50" height="50" />
OneapproachtoaddressingthisissueistoadoptapolicyofalwayshavingyourURLsentirelyin lowercase.
Fordynamiccontent,itmightalsomakesensetocheckformixed-caseincomingURLsinan ASP.NETHttpModule,sothatyoucandetectandcompensateforanymarkuporexternalsitesthat referenceorgeneratesuchURLs.Todetermineifthisisanissueforyoursite,youcouldincrementa performancecountertoprovideanindicationofhowoftentheserverencounterssuchURLs,oryou couldwritetheURLanditsreferrertoalog,orexaminetheIISlogs.IcoverHttpModulesinChapter7.
ThebrowsercacheassociatesaparticularURLwithsomecontent,soforbestperformanceyou shouldalwaysreferenceidenticalcontentusingidenticalURLs.Ifyouarerunningseveralsites,youcan improveperformancebyusingashareddomainforcommonstaticcontent.Forexample,ifyou’re runningbothwww.12titans.netandwww.apress.comandthere’sagoodchancethatvisitorstoonesite willalsovisittheother,thenyoumightwanttohaveathirddomainorsubdomain(oraCDN),suchas
static.12titans.net,thatbothsitescanuseforcommonstaticcontent.
Asimilarstrategyalsoappliestoyourdomainname.Ifyouhaveseveraldifferentdomainsthatrefer tothesamesite,youcanimproveclient-sidecachingifyoureferencethemconsistentlyandhelpusers dothesame.Forexample,youmightinsteadredirectallreferencesfromdomainslike12titans.netand
www.12titans.comtowww.12titans.net,ratherthanservingidenticalcontentfromallthreedomains. Otherwise,auserwhovisitedthesitefirstwithonedomainnameandthenwithanotherwouldneedto downloadallcacheablecontenttwiceinsteadofonlyonce.Keepinmindthatyoucan’tcontrolhow otherslinktoyoursite.Youmightbeconsistentonyoursiteaboutusingwww,butanothersitecouldlink toyouwithoutit.
Mergingidenticaldomainsalsohelpswithsearchengineoptimization.It’spossiblethatsearch engineswillexcludeorotherwisepenalizeyoursiteiftheyseemanycopiesofidenticalcontent.
NetworkOptimizations
WhenIEdoesn’tfindimagesandotherresourcesinitscache,itplacesrequeststoretrievethemin queuesthatitserviceswithamaximumofsixconnectionsperdomain.
Note
Browsersdon’tlookattheIPaddressofadomainwhendeterminingwhethertoopenanewconnection;
theydoadirectstringcomparisonofthedomainnames(ignoringcase).
ConsiderthefollowingHTML(seefile03.htm):
<img src="q1.gif" height="16" width="16" /> <img src="q2.gif" height="16" width="16" /> <img src="q3.gif" height="16" width="16" /> <img src="q4.gif" height="16" width="16" /> <img src="q5.gif" height="16" width="16" /> <img src="q6.gif" height="16" width="16" /> <img src="q7.gif" height="16" width="16" /> <img src="q8.gif" height="16" width="16" /> <img src="q9.gif" height="16" width="16" /> <img src="q10.gif" height="16" width="16" />
ThefirstrowshowsthetimetoopentheconnectionandreadtheHTML.Thenextrowshowsthe firstimagebeingrequested,whichusesthesameconnectionasthefirstrequest.ThethirdrowshowsIE startingtherequestforthesecondimageatthesametimeasthefirst,whichrequiresanewconnection. Therequestsforthenextfourimagesstartafterashortdelay,butareactiveatthesametimeasthefirst twoimages,indicatingthattheyareusingtheirownconnections.
Iftheserverpermits,IEkeepsthoseconnectionsopenaftertherequestscomplete.Aftereach requestcompletes,IEstartsanewrequest;thebeginningoftheactivepartofeachrowcorrespondsto theendofanearlierrow.
Let’schangetheHTMLtorequestfiveimagesfromeachoftwodifferentdomains(seefile04.htm):
<img src="q1.gif" height="16" width="16" /> <img src="q2.gif" height="16" width="16" /> <img src="q3.gif" height="16" width="16" /> <img src="q4.gif" height="16" width="16" /> <img src="q5.gif" height="16" width="16" />
<img src="http://s1.12titans.net/samples/ch02/q6.gif" height="16" width="16" /> <img src="http://s1.12titans.net/samples/ch02/q7.gif" height="16" width="16" /> <img src="http://s1.12titans.net/samples/ch02/q8.gif" height="16" width="16" /> <img src="http://s1.12titans.net/samples/ch02/q9.gif" height="16" width="16" /> <img src="http://s1.12titans.net/samples/ch02/q10.gif" height="16" width="16" />
Here’stheresultingtimeline:
ThesequenceofeventsisthesamefortheHTMLandthefirstfewimages.However,nowIE requestsalloftheotherimagesatthesametime.Thispageloadsinabouthalftoathirdofthetimeas theoriginal.
Youcantakeadvantageofparallelobjectdownloadsbystrategically(andconsistently)usingseveral differentdomainsorsubdomainsforyourstaticcontent.Becauseittakesalittlewhiletoopenanew TCPconnectionandthebrowserlimitsthemaximumnumberofsimultaneousconnections,agoodrule ofthumbistoloadyourstaticcontentfromtwoorthreedomains.Youmightwanttohaveseveral domainaliasesforyoursite.Thatallowsyoutooptimizedownloadparallelismbysimplyadjustingthe domainnamesinyourpages,withouthavingtomanagewhichcontentisinwhichdomain.Consider automatingtheprocessofassigningstaticfilestoparticulardomainsusinganASP.NETcontroladapter (seeChapter7)—justbesuretouseaconsistentdomainforeachresource,toavoidunwantedcache misses.
JavaScriptGroupingandPlacement
Toreduceround-trips,youshouldhaveasfewscriptfilesaspossible.Youcanarrangethisbydoingone ormoreofthefollowing:
• Combinethemtogetherstatically(suchaswithaneditor) • Combinethemtogetherdynamically,either:
• Asacompilepost-processingstepor
• Programmatically(on-demand)whenthebrowserrequeststhescript.The .NETFrameworksupportsautomatedbundling,whichIcoverin
Chapter6.
Mid-documentscriptincludescancausethebrowsertodelayrenderingthepageuntilafterthe scriptfilearrives.Fromaperformanceperspective,it’sbettertoplaceyourincludesattheendofyour HTMLwhenyoucan.Acommonreasonforusingmid-documentscriptincludesistoinsertHTMLinto thepageusingdocument.write().
• Insteadofdocument.write(),useinnerHTMLordirectDOMmanipulation,which youcandolateintheHTML
• Ifyoucan’tavoiddocument.write()(suchaswithscriptsfromthird-parties),then insteadofusingmultiple<script>files,either:
• Wrapthescriptwithabsolutepositioningandrunitlateinthefile,or • Runthescriptinahidden<div>,andthenmovethecontentsofthe<div>
intoitsdesiredlocationbymanipulatingtheDOMusingJavaScript
Avoidingdocument.write()
Here’ssomescriptthatdoesaninlinedocument.write()(seeimg1.js):
ThepatterntoavoidistheonethatincludesthescriptinthemiddleofyourHTML(seefile06.htm):
<div>
<script type="text/javascript" src="img1.js"></script> </div>
OnealternativeistosetavariabletoastringcontainingtheHTMLthatyouwanttoinsertonthe page(seeimg2.js):
var qimg = '<img src="q1.gif" height="16" width="16" />';
IncludethescriptfileattheendoftheHTML(seefile07.htm):
<style type="text/css"> #exd{height:16px;width:16px} </style>
<div id="exd"> </div>
<script type="text/javascript" src="img2.js"></script> <script type="text/javascript">
document.getElementById('exd').innerHTML = qimg; </script>
AddthenewHTMLtotheDOMusingtheinnerHTMLpropertyofacontaining<div>.Assignthe<div> tagawidthandheighttomatchtheimagetoavoidHTMLpagere-layoutswhenitscontentsareupdated (doneintheexampleusingCSS).
Here’sanotherapproach(seeimg3.js):
function putimg(qdiv) {
var myim = new Image(16, 16); myim.src = "q1.gif";
qdiv.appendChild(myim); }
Thescriptisincludedattheendoffile08.htm:
<style type="text/css"> #exd{height:16px;width:16px} </style>
<div id="exd"> </div>
<script type="text/javascript" src="img3.js"></script> <script type="text/javascript">
putimg(document.getElementById('exd')); </script>
Thistime,useafunctiontocreateanImageobjectandappenditasachildoftheDOMnodeofthe
<div>.
ReorderingScriptThatYouCan’tModify
<div>
<script type="text/javascript" src="img1.js"></script> </div>
<div> Lorem Ipsum </div>
TomovethescripttotheendoftheHTML,youcanassignabsolutepositionstobothofthe<div> tagsandthenreversetheirorder(seefile10.htm):
<style type="text/css">
.content,.banner{position:absolute; left:10px} .content{top:40px}
.banner{top:10px} </style>
<div class="content"> Lorem Ipsum
</div>
<div class="banner">
<script type="text/javascript" src="img1.js"></script> </div>
Alternatively,youcancallthescriptinahidden<div>andthenmovethatDOMnodeintoposition (seefile11.htm):
<style type="text/css"> .temp{display:none}
#banner{height:20px;width:16px} </style>
<div id="banner"> </div>
<div> Lorem ipsum </div>
<div class="temp"> <div id="mystuff">
<script type="text/javascript" src="img1.js"></script> </div>
</div>
<script type="text/javascript">
var ba = document.getElementById('banner'); var ms = document.getElementById('mystuff'); if ((ba != null) && (ms != null))
ba.appendChild(ms); </script>
RequestingImagesandOtherObjectsAfterthePageLoads
Youcancombineuseofthepageonloadhandlerwiththelateimageloadtechniquetomakeverylate requests,aftereverythingelseonthepagehasdownloaded.Rolloverimagesareanexample,sincethey don’tneedtobedisplayedwhenthepageisinitiallyrendered,butiftheyareeventuallyused,theuser experiencewillbemuchbetteriftheyarealreadyinthebrowser’scache(imagespritesortransparency variationsaregenerallyabettersolutionsforrolloverimages;seethesections“ImageSpritesand Clustering”and“UseTransparencyasanAlternativetoRolloverImages”fordetails).Large,low-priority images,orimagesthatarebelowthefoldareothercandidatesforlateloading.
Here’sanexample(seefile12.htm):
<body onload="lateimage()">
<img id="slow" height="16" width="16" /> <div>
Lorem ipsum </div>
<script type="text/javascript"> function lateimage() {
document.getElementById('slow').src = "big.jpg"; }
</script>
An<img>tagwithanid,height,andwidth,butwithoutsrc,isaplaceholderfortheimage.Thenthe
<body>onloadhandlersetsthesrcofthe<img>tagtobethepathtotheimage,whichcausesthebrowser toloadtheimage.
Note
AlthoughitwasfixedinIE9,don’tbetemptedtouseanemptystringforthe
srctag.Doingsocancause
olderbrowserstoissuea
GETrequestforthecurrentfolder’sdefaultdocument,asthoughyouset
src="./"
UsingjQuerytodothesamethingmakesiteasytoavoidchangingthe<body>tag:
<body>
<img id="slow" height="16" width="16" /> <div>
Lorem ipsum </div>
<script type="text/javascript"> $(window).load(function () {
$('#slow').attr('src', 'big.jpg'); });
</script>
ScriptDeferandAsync
Using<script defer>cansometimeshelpimprovetheperformanceofapagebydelayingthepointat whichthebrowserparsesandexecutestheassociatedscriptuntilafterthepagehasloaded.