为了提高网站性能并减少文件总返回值,您可以考虑在需要时加载JavaSript(.js)文件。 在jQuery中,您可以使用$ .getScript函数在运行时或按需加载JavaScript文件。
例如,
$("#load").click(function(){
$.getScript('helloworld.js', function() {
$("#content").html('Javascript is loaded successful!');
});
});
单击具有“加载” ID的按钮时,它将动态加载“ helloworld.js ” JavaScript文件。
自己尝试
在此示例中,当您单击加载按钮时,它将在运行时加载“ js-example / helloworld.js ”,其中包含一个“ sayhello() ”函数。
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<h1>Load Javascript dynamically with jQuery</h1>
<div id="content"></div>
<br/>
<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>
<script type="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>
标记: JavaScript jQuery
翻译自: https://mkyong.com/jquery/how-to-load-javascript-at-runtime-with-jquery/