远程加载 耗时javascript 脚本时,没法取消其执行

1. 问题描述

   在做网络应用程序时,经常会有这样的情况产生,用户在前端操作过快时,会以较快的时间间隔向服务器发送请求,而服务器端会返回 JS 脚本更改客户端的状态,在这种情况下,服务器端返回的 JS 脚本会发生重叠,我们可能想如果在用户发送请求时判断前一次请求的结果是否已返回,如果没有返回,则取消掉前次的请求结果。

 

2. 代码模拟

  用户请求的 前台页面

  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>远程脚本加载过程中删除脚本的效果</title>

    <script type="text/javascript">
        var loadJS = function (url, success, id) {
            
          var domScript = document.createElement('script');
          domScript.src = url;          
          domScript.id = id;
          document.getElementsByTagName('head')[0].appendChild(domScript);
          

          setTimeout(function() {
            domScript.parentNode.removeChild(domScript);
          }, 500);

        };

        function load_remote_script() {
            loadJS('http://localhost/project/test/JS-Program/remote_script_loading_del_effect/remote.php', null, 'remote');
        }
    </script>
</head>
<body>
    <input type="text" id="info" />
    <button onclick="load_remote_script()">加载远程脚本</button>
</body>
</html>

模拟服务器端生成JS脚本的页面(用PHP编写)

<?php 

sleep(3);

echo "document.getElementById('info').value++;"


 ?>

3. 测试总结

  点击 加载远程脚本按钮后, 在0.5s后就从 HTML页面中 remove掉脚本。发现 input 中的值还是增加了。即使在 remove 掉脚本后,立刻将 domScript =null ,结果也是一样。

 结论:尽管在返回脚本前就把脚本从页面中移除,脚本返回后的代码依然执行。

 

4. 可能的方案

  一旦加载脚本后,除非出现页面错误,浏览器会一定会执行该脚本返回后的内容。该怎么解决这个问题呢,我觉得可以在返回的 脚本中解决。如下所示:

  

<?php 

sleep(3);

echo "if(document.getElementById('remote')) document.getElementById('info').value++;"


 ?>

 

posted @ 2013-03-26 12:20  风影无忌  阅读(333)  评论(0编辑  收藏  举报