动态加载 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7293344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load JavaScript dynamically
提问by Giuseppe Di Federico
I have a web page and a canvas with Google Maps embedded in it. I am using jQuery on this site.
我有一个网页和一个嵌入了谷歌地图的画布。我在这个网站上使用 jQuery。
I want to load Google Maps API only if the user clicks on "Show me the map". Further, I want to take away the whole loading of the Google Maps from the header in order to improve my page performance.
我只想在用户单击“显示地图”时加载 Google Maps API。此外,我想从标题中删除 Google 地图的整个加载,以提高我的页面性能。
So I need to load JavaScript dynamically. What JavaScript function I can use?
所以我需要动态加载 JavaScript。我可以使用什么 JavaScript 函数?
回答by Arnaud Leymet
You may want to use jQuery.getScriptwhich will help you load the Google Maps API javascript file when needed.
您可能希望使用jQuery.getScript,它可以帮助您在需要时加载 Google Maps API javascript 文件。
Example:
例子:
$.getScript('http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true', function(data, textStatus){
console.log(textStatus, data);
// do whatever you want
});
回答by user278064
Use the Loading on DemandLoading Strategy
使用按需加载加载策略
Loading on Demand
按需加载
The previous pattern loaded additional JavaScript unconditionally after page load, assuming that the code will likely be needed. But can we do better and load only parts of the code and only the parts that are really needed? Imagine you have a sidebar on the page with different tabs. Clicking on a tab makes an XHR request to get content, updates the tab content, and animates the update fading the color. And what if this is the only place on the page you need your XHR and animation libraries, and what if the user never clicks on a tab?Enter the load-on-demandpattern. You can create a require() function or method that takes a filename of a script to be loaded and a callback function to be executed when the additional script is loaded.
前面的模式在页面加载后无条件加载了额外的 JavaScript,假设可能需要代码。但是我们能否做得更好,只加载部分代码和真正需要的部分?想象一下,您在页面上有一个带有不同选项卡的侧边栏。单击选项卡会发出 XHR 请求以获取内容、更新选项卡内容并动画淡化颜色。 如果这是页面上唯一需要 XHR 和动画库的地方,并且用户从不单击选项卡怎么办?输入按需加载模式。您可以创建一个 require() 函数或方法,该函数或方法采用要加载的脚本的文件名以及加载附加脚本时要执行的回调函数。
The require() function can be used like so:
require() 函数可以这样使用:
require("extra.js", function () {
functionDefinedInExtraJS();
});
Let's see how you can implement such a function. Requesting the additional script is straightforward. You just follow the dynamic element pattern. Figuring out when the script is loaded is a little trickier due to the browser differences:
让我们看看如何实现这样的功能。请求附加脚本很简单。您只需遵循动态元素模式。由于浏览器的差异,确定何时加载脚本有点棘手:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
newjs.onreadystatechange = null;
callback();
}
};
// others
newjs.onload = function () {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
“JavaScript Patterns, by Stoyan Stefanov (O'Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”
“JavaScript 模式,作者 Stoyan Stefanov (O'Reilly)。版权所有 2010 Yahoo!, Inc.,9780596806750。”
回答by rlemon
you would just generate the script tag via javascript and add it to the doc.
您只需通过 javascript 生成脚本标记并将其添加到文档中。
function AddScriptTag(src) {
var node = document.getElementsByTagName("head")[0] || document.body;
if(node){
var script = document.createElement("script");
script.type="text/javascript";
script.src=src
node.appendChild(script);
} else {
document.write("<script src='"+src+"' type='text/javascript'></script>");
}
}
回答by Tanjim Hossain
I think you're loking for this http://unixpapa.com/js/dyna.html
我想你正在寻找这个http://unixpapa.com/js/dyna.html
<input type="button" onclick="helper()" value="Helper">
<script language="JavaScript">
function helper()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'your_script_url';
head.appendChild(script);
}
</script>
回答by infinito84
I used the Tangim response, but after found that is more easy use jquery html() function. When we make ajax request to html file that have html+javascript we do the follow:
我使用了 Tangim 响应,但后来发现使用 jquery html() 函数更容易。当我们向具有 html+javascript 的 html 文件发出 ajax 请求时,我们执行以下操作:
$.ajax({
url:'file.html',
success:function(data){
$("#id_div").html(data); //Here automatically load script if html contain
}
});