Tải bản đầy đủ - 0 (trang)
Hack 80. Use Strings and Arrays to Dynamically Generate HTML

Hack 80. Use Strings and Arrays to Dynamically Generate HTML

Tải bản đầy đủ - 0trang

functionbuildTable(nRows,nCols){

varidx=0,idx2=0;

varoTable=document.createElement("TABLE");

varoTBody=document.createElement("TBODY");

varoTRow=null;

varoTCol=null;

for(idx;idx
oTRow=document.createElement("TR");

for(idx2=0;idx2
oTCol=document.createElement("TD");

oTCol.innerText=nRow+","+nCol;

oTCol.style.fontSize="12px";

oTCol.style.fontWeight=700;

oTCol.style.fontFamily="tahoma";

oTRow.appendChild(oTCol);

};

oTBody.appendChild(oTRow);

};

oTable.appendChild(oTBody);

document.body.appendChild(oTable);

};



Andhere'sthesecondapproach:

functionbuildTable(nRows,nCols){

varidx=0,idx2=0;

varbufferHTML=newArray();

varbufferCount=0;

bufferHTML[bufferCount++]="";

for(idx;idx
bufferHTML[bufferCount++]="
";

for(idx2=0;idx2
bufferHTML[bufferCount++]=



"
"tahoma;font-weight:700'>";

bufferHTML[bufferCount++]=nRow;

bufferHTML[bufferCount++]=",";

bufferHTML[bufferCount++]=nCol;

bufferHTML[bufferCount++]="";

};

bufferHTML[bufferCount++]="
";

};

bufferHTML[bufferCount++]="
";

document.body.innerHTML+=bufferHTML.join("");

};



UsingarraysandstringstowriteHTMLdynamicallyintothepage

is,relatively,fasterthanusingtheDOMAPIs.



Runningatestprogramthattimesthetwocodepiecesindicatesthat

theDOMtable-writingexampletookroughlytwiceasmany

millisecondstorunasthesecondcodesample(about1000ms,

comparedwith500).



PerformanceMatters

Inthesecondcodesample,thecodeaccessestheDOMwith

onecodeline,ratherthanwithseveralmethodcallsasinthe

firstexample:

document.body.innerHTML+=bufferHTML.join("");



Inaddition,thecodeusesanArrayobjecttostoreallthevarious

piecesoftheHTMLstring.Thisstrategyavoidsusing

unnecessaryCPUcyclestocontinuallyconcatenatenewpieces

oftexttothestring(similartoajava.lang.StringBufferobjectin

theJavalanguage).

TherearetimeswhenusingonlystringstobuildHTMLisnotan

option;thecodehastomakeaDOMcalltocreateorchange

thecontentofaparticularelement.Thefollowingcodesamples

illustratetwomoreexamplesofhowthiscanbedone.

Hereisoneexamplethatchangesawebpageelement

dynamically.Thefunctionchangestheappearanceofan

elementbyaccessingtheelement'sstyleproperty,thusaltering

itsvisualaspects(suchasthesizeandcolorofthefont):

functionchangeElementContents(sID){

varoEl=document.getElementById(sID);

oEl.style.fontWeight=700;

oEl.style.fontFace="Arial";

oEl.style.fontSize="20px";

oEl.style.backgroundColor="red";

oEl.style.color="white";

oEl.innerHTML="HelloWorld,ContentsChanged";

oEl.noWrap=true;

};



Thesecondversionofthistaskminimizesthenumberoftimes

thecodeaccessesDOMAPIsbyreducingthenumberof.style

references:

functionchangeElementContents(sID){

varoEl=document.getElementById(sID);



with(oEl){

style.cssText=

"font-weight:700;font-face:Arial;font-size:20px

"background-color:red;color:white;";

innerHTML="HelloWorld,ContentsChanged";

noWrap=true;

};

};



Inaddition,thestyle.cssTextpropertyallowsthecodetochange

allCSSstylepropertiesinoneshot,ratherthanalteringthem

piecebypiece.Similaroptimizationstrategiesmayimprovethe

performanceoflargeprogramsthatincludealotofDOM

scripting.



Eventhoughanumberoftutorialsandblogsdonotrecommendusing

with,thewithstatementcanprovideasmallincreaseinperformanceif

usedcorrectly.However,developersshouldbewaryaboutputtingany

othercodeinsideawithblockunlessitstrictlydealswithsettingthe

valuesofexistingobjectproperties.



SeanSnider







Index

[SYMBOL][A][B][C][D][E][F][G][H][I][J][L][M][N][O]

[P][Q][R][S][T][U][V][W][X][Y][Z]



Index

[SYMBOL][A][B][C][D][E][F][G][H][I][J][L][M][N]

[O][P][Q][R][S][T][U][V][W][X][Y][Z]

#(hashmark)

@(atsign)

^(caret)



\\

\\

(colons,doubled)

/**/(commentcharacters,JavaScript)

$(dollarsign)

//(forwardslashes)



<%=javascript_include_tag\\

defaults%>embeddedtag

<%...%>(Rubyscripttags)



{}(curlybraces)

exceptiontrappingand

JSONnotationand



Index

[SYMBOL][A][B][C][D][E][F][G][H][I][J][L][M][N]

[O][P][Q][R][S][T][U][V][W][X][Y][Z]

a_complete()method

abort()method

Accept-Languagerequestheaders

actions2nd3rd

create_select

increment

show_env

zero_updateaction

ActiveXprogramIDsforMicrosoftrequestobjects

add()function

addOptions()function

addOptionValues()function

addToBullets()function

addToChecks()function

Ajax

back-buttonand

bookmarkinglibraries

historylibraries

maintenanceandperformance,enhancement

tagdebuggingwithFirefox

webpagedata,caching



Ajax(AsynchronousJavaScriptandXML)2nd

includedtechnologies

limitations

uses



AjaxMassiveStorageSystem[SeeAMASS]

Ajax.Autocompleterobject

Ajax.InPlaceEditorobject

Ajax.Requestobject

go_urlparameter

Ajax.Updaterobject2nd

ajaxEnginevariable

Ajaxy

allInputsvariable

AMASS(AjaxMassiveStorageSystem)

requirements

anchorhash

Apache,configurationforcross-domainissues

applicationID,YahooMapsAPI

applicationmaintenance

bashshellscript

cachingissues

JavaScriptfilecompression

JavaScriptfiles,merging

application.js

applyLuhn()function

associativearrays

async_cmd()function2nd

auto-completefields

auto-completion

auto_com.js

auto_inp.js



autocompletefields

script.aculo.us,using

autocomplete()function

aync_cmd()function



Index

[SYMBOL][A][B][C][D][E][F][G][H][I][J][L][M][N]

[O][P][Q][R][S][T][U][V][W][X][Y][Z]

back-button,fixinginAjaxapplications

iframesandbbfix.js,with

RSH,using

Backbase

bb_save_state()function

bbfix.js2nd

BikeBeanclass

BikeJavaBeanclass

blank.html

bookmarklets

bookmarks,fixinginAjaxapplications



browsers

back-buttonandAjax

fixing

compatibilitydetection

if/thentesting

cross-domainrequesthandling

fillingformswithoutrefreshes

history,controllingwithiframes

localeinformation,finding

searchengines,runninginside



serverdata,displaywithoutrefreshes

texthandlingquirks



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 80. Use Strings and Arrays to Dynamically Generate HTML

Tải bản đầy đủ ngay(0 tr)

×