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

来源:互联网 发布:陌陌mac版官方下载 编辑:程序博客网 时间:2024/05/01 01:51

为了提高站点的性能和减少返回的所有文件的大小,你也许想在需要的时候才去装载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 的效果:
0 0
原创粉丝点击