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

为了提高站点的性能和减少返回的所有文件的大小,你也许想在需要的时候才去装载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!");
}


初始效果:
怎么使用jquery在运行时装载javaScript文件_第1张图片
点击load javascript 按钮后:

怎么使用jquery在运行时装载javaScript文件_第2张图片
接着点击say hello 的效果:

怎么使用jquery在运行时装载javaScript文件_第3张图片


你可能感兴趣的:(jquery翻译)