您的位置:首页 > Web前端 > JQuery

怎么使用jquery在运行时装载javaScript文件

2014-10-16 23:32 253 查看
为了提高站点的性能和减少返回的所有文件的大小,你也许想在需要的时候才去装载JavaScript(.js)文件。在jquery,你能够使用$.getScript函数来按需或在运行时装载(下载)JavaScript文件。例如:
$("#load").click(function(){
        $.getScript('helloworld.js', function() {
                $("#content").html('Javascript is loaded successful!');
        });
});
当一个id为load的按钮被点击时,helloworld.js文件将会在运行时动态的装载。 注意:$.getScript 是采用异步请求,来实现的。你可自己去试一下: 在一下的例子中,当点击load按钮,它将会装载helloworld.js文件,此文件有一个sayhello()函数。
<html>
<head>
 
<scripttype="text/javascript"src="jquery-1.4.2.min.js"></script>
 
</head>
<body>
  <h1>Load Javascript dynamically with jQuery</h1>
 
<divid="content"></div>
<br/>
 
<buttonid="load">Load JavaScript</button>
<buttonid="sayHello">Say Hello</button>
 
<scripttype="text/javascript">
 
$("#load").click(function(){
  $.getScript('js-example/helloworld.js', function() {
     $("#content").html('
          Javascript is loaded successful! sayHello() function is loaded!
     ');
  });
});
 
$("#sayHello").click(function(){
  sayHello();
});
 
</script>
</body>
</html>
helloworld.js 文件内容为:
function sayHello(){alert("Hello ~ jQuery!");}
初始效果:
点击load javascript 按钮后:
接着点击say hello 的效果:

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery翻译
相关文章推荐