基礎寫法
function load(targetId,templateName) { $("#"+targetId).load(contextPath+templateName); }
陷阱1: 異步加載問題
由於load是異步觸發的,以下方法中的2行代碼都是同時並發執行的,由於網絡延遲等問題,哪句先執行並不確定.
而id為templateId的<div id="templateId">init</div>元素又是通過load加載進來的.
如果是后面第3行的$("#templateId").html("hellow");先執行,那么由於$("#templateId")找不到(此時尚未加載完div),其實並不會執行html("hellow")操作.
1 function load(targetId,templateName) { 2 $("#"+targetId).load(contextPath+templateName); 3 $("#templateId").html("hello"); 4 }
陷阱2: 緩存問題
由於很多瀏覽器為了降低請求服務器的負荷,做了同樣的請求地址,從本地緩存取歷史數據的優化.所以我們需要在地址后面添加一些動態后綴.
function load(targetId,templateName) { var nowDate = new Date(); var randomId = nowDate.getTime();//防緩存 $("#"+targetId).load(contextPath+templateName+"?"+randomId); }
陷阱3: 結構破壞問題
在陷阱1(緩存問題)的基礎上,可能還會遇到更深層次的問題,那就是當我們load加載得到的數據如果不符合<html>規范,那么就會破壞原有的dom結構,導致后續取dom和其它節點異常.
比如原有
<html lang="cn"> <head> <title>test</title> </head> <body> <textarea id="mytext"></textarea> </body> </html>
如果load得到的數據為 <textarea><
那么最終生成了為不規則的html閉包.下次再取dom時可能取不到了,因為破壞了原有的結構
<html lang="cn"> <head> <title>test</title> </head> <body> <textarea id="mytext"><textarea><</textarea> </body> </html>
此時我們可以改成
function load(targetId,templateName) { var nowDate = new Date(); var randomId = nowDate.getTime();//防緩存 $("#"+targetId).load(contextPath+templateName+"?"+randomId,{},function (responseTxt){ $("#"+targetId).val(responseTxt); }); }
此時生成的html元素不會作為dom節點,而是作為文本域的原始文本插入,也就沒有破壞原始dom.所以下次取值還是正常的
<!doctype html> <html lang="cn"> <head> <title>test</title> </head> <body> <textarea id="mytext">"\<textarea\>\<"</textarea> </body> </html>
總結
其實
$("#"+targetId).load(contextPath+templateName+"?"+randomId)
就是調用了html(xxx)
function load(targetId,templateName) { var nowDate = new Date(); var randomId = nowDate.getTime();//防緩存 $("#"+targetId).load(contextPath+templateName+"?"+randomId,{},function (responseTxt){ $("#"+targetId).html(responseTxt); }); }