谨慎使用Ajax动态引入Js(附代码与结果)

代码(index.php):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html><head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>console.log("header",new Date());</script>
</head><body ryt12134="1">
<script>console.log("body_header",new Date());</script>
<script>
(function($) {
    $(function() {
        console.log("$$$$" + new Date());
    });
})(jQuery);
$(document).ready(function(){ console.log("ready",new Date());});
</script>
<script type="text/javascript" src="http://42.121.117.187:8899/test.js?<?php echo time();?>"></script>
<script>console.log("body_footer",new Date());</script>
</body></html>

代码(index.html):

1
2
3
4
5
6
7
8
<html><head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script></head><body ryt12134="1">
<script>
$.get("index.php",function(html){
    $("body").append(html);
});
</script>
</body></html>

测试结果:macos:firefox、chrome、safari -- win8:ie10 基本相同

  1. 将js文件放在header中,document.ready()会等待js加载完成后再执行(header中的js是优先于body加载的)
  2. 将js文件放在body中,则 不考虑js是否加载就会执行(将jquery放在最后面,会导致js出错)
  3. 直接请求index.php的执行结果

    header Date {Thu Aug 29 2013 14:32:51 GMT+0800 (CST)}
    body_header Date {Thu Aug 29 2013 14:32:51 GMT+0800 (CST)}
    qian_test.js Date {Thu Aug 29 2013 14:32:54 GMT+0800 (CST)}
    hou_test.js Date {Thu Aug 29 2013 14:32:54 GMT+0800 (CST)}
    body_footer Date {Thu Aug 29 2013 14:32:54 GMT+0800 (CST)}
    $$$$Thu Aug 29 2013 14:32:54 GMT+0800 (CST)
    ready Date {Thu Aug 29 2013 14:32:54 GMT+0800 (CST)}
    
  4. 请求index.html的执行结果(显然document.ready优先于js中的代码执行)

    header Date {Thu Aug 29 2013 14:44:01 GMT+0800 (CST)}
    body_header Date {Thu Aug 29 2013 14:44:01 GMT+0800 (CST)}
    $$$$Thu Aug 29 2013 14:44:01 GMT+0800 (CST)
    ready Date {Thu Aug 29 2013 14:44:01 GMT+0800 (CST)}
    body_footer Date {Thu Aug 29 2013 14:44:01 GMT+0800 (CST)}
    qian_test.js Date {Thu Aug 29 2013 14:44:04 GMT+0800 (CST)}
    hou_test.js Date {Thu Aug 29 2013 14:44:04 GMT+0800 (CST)}