ajax之$.getScript()

$.getScript()

原文作者链接

有时候,在页面初次加载时就取得所需的全部JavaScript文件是完全没有必要的。虽然可以在需要哪个JavaScript文件时,动态地创建<script>标签,jQuery代码如下:

$(document.createElement("script")).attr("src","test.js").appendTo("head");

  或者

$("<script type='text/javascript' src='test.js' />").appendTo("head");

但这种方式并不理想。为此,jQuery提供了$.getScript()方法来直接加载.js文件,与加载一个HTML片段一样简单方便,并且不需要对JavaScript文件进行处理,JavaScript文件会自动执行。 
demo实例如下:

demo1.html

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <title></title>
 5  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 6 <style type="text/css">
 7 * { margin:0; padding:0;}
 8 body { font-size:12px;}
 9 .comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
10 .comment h6 { font-weight:700; font-size:14px;}
11 .para { margin-top:5px; text-indent:2em;background:#DDD;}
12 </style>
13  <!--   引入jQuery -->
14 <script src="../scripts/jquery.js" type="text/javascript"></script>
15 <script type="text/javascript">
16    $(function(){
17         $('#send').click(function() {
18             $.getScript('test.js');
19         });
20    })
21    </script>
22 </head>
23 <body>
24  <br/>
25  <p>
26      <input type="button" id="send" value="加载"/>
27  </p>
28 
29 <div  class="comment">已有评论:</div>
30  <div id="resText" >
31 
32  </div>
33 
34 </body>
35 </html>

test.js代码:

 1 var comments = [
 2   {
 3     "username": "张三",
 4     "content": "沙发."
 5   },
 6   {
 7     "username": "李四",
 8     "content": "板凳."
 9   },
10   {
11     "username": "王五",
12     "content": "地板."
13   }
14 ];
15 
16   var html = '';
17   $.each( comments , function(commentIndex, comment) {
18       html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
19   })
20 
21   $('#resText').html(html);

当执行到demo1.html中的jQuery的时候,页面就会加载test.js文件。 
jQuery代码如下:

$(function(){
  $('#send').click(function() {
    $.getScript('test.js');
  });
});

与其他Ajax方法一样,$.getScript()方法也有回调函数,它会在JavaScript文件成功载入后运行。例如像载入jQuery官方颜色动画插件(jquery.color.js),成功后给元素绑定颜色变化动画,就可以用到$.getScript()方法的回调函数。代码如下:

1 $(function(){
2   $.getScript('jquery.color.js',function(){
3     $("<p>加载JavaScript完毕</p>").appendTo("body");
4       $("#go").click(function(){
5       $(".block").animate( { backgroundColor: 'pink' }, 1000).animate( { backgroundColor: 'blue' }, 1000);
6     });
7   });
8 });

当jquery.color.js动画插件加载完毕后,单击id为“go”按钮时,class为block的元素就有了颜色动画变化。

本人小白,博客作为在线笔记,若有错误,还望指出,转载链接截图等皆为学习,若有侵权,请告知,
原文地址:https://www.cnblogs.com/xiaoxiaoyao/p/8623228.html