2022.2

Table Of Contents
Inthisexample,@product@isapattern(tobeusedinasearch)andgisamodifier(tofindall
matchesratherthanstoppingafterthefirstmatch).Formoreinformationaboutpossibleregular
expressions,seehttps://www.w3schools.com/js/js_regexp.asp.
Replaceseveralplaceholdersinonescript
Supposethereare20differentplaceholdersinapostcard(fortheaddress,accountandcustomer
details,apromocode,theduedate,discounts,alinktoapersonalizedlandingpageetc.).Typicallythis
wouldrequire20queries.EvenafteroptimizingthesescriptsbyusinganIDasselectorforthose
scripts,therearestill20scripts,20queriestorun.
Iftherewasonlyonequery,onesinglescripttodoallthework,theoutputcouldbegeneratedmuch
faster.Reducingthenumberofscriptsimprovestheperformanceofthetemplate.Howtodothis?
First,wrapthecontentthatcontainsalloftheplaceholdersinone(inline)BoxandgivethatBoxor
SpananID(ontheAttributespane).Next,createascriptthatusesthatIDasselector.Thenreplaceall
placeholdersinthescriptandputthecontentbackinthetemplate.
Thisissimilartoworkingwithsnippets,butinthiscasetheelementisextractedfromtheactualtem-
plate.
Example: Thefollowingscriptreplacesalloftheplaceholdersonapostcard.Ittakesadvantage
oftheJavaScriptreplace()command.AssumingthattheIDoftheblockthatrequiresper-
sonalizationispromoblock,thescripthastohaveitsselectorsetto#promoblock.
var block = results.html();
var data = record.fields;
block = block.replace('@name@',data.first + ' ' + data.last);
block = block.replace('@address@',data.address);
block = block.replace('@zip@',data.zip);
block = block.replace('@city@',data.city);
block = block.replace('@country@',data.country);
block = block.replace('@saldo@',data.saldo);
block = block.replace('@promo@',data.promo);
block = block.replace('@customercode@', data.customercode);
results.html(block);
ThefirstlineretrievestheHTMLofthepromoblockandstoresitinavariablecalledblock.Tomakethe
codemorereadible,thefieldsfromtherecordarestoredinavariablenameddata.Afterreplacingthe
placeholdersbyvalues,thescriptreplacestheHTMLofthepromoblockwiththepersonalizedstring.
Otherresources
TherearealsomanyresourcesonlinetohelplearnaboutJavaScriptperformanceandcodingmis-
takes.Seeforexample:
l
JavaScriptperformance
l
The10mostcommonJavaScriptmistakes
Page 383