jquery load 陷阱【原】

基础写法

        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);
            });
        }
原文地址:https://www.cnblogs.com/whatlonelytear/p/7887059.html