Load JavaScript dynamically
我有一个网页和一个嵌入谷歌地图的画布。我在这个网站上使用jquery。
我只想在用户单击"显示地图"时加载GoogleMapsAPI。此外,为了提高我的页面性能,我想从标题中去掉整个谷歌地图的加载。
所以我需要动态加载javascript。我可以使用什么javascript函数?
您可能需要使用jquery.getscript,它将帮助您在需要时加载Google地图API javascript文件。
例子:
1 2 3 4 | $.getScript('http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true', function(data, textStatus){ console.log(textStatus, data); // do whatever you want }); |
使用按需加载策略
按需加载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-demand pattern. 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.
require()函数的用法如下:
1 2 3 | require("extra.js", function () { functionDefinedInExtraJS(); }); |
让我们看看如何实现这样一个函数。请求附加脚本是直截了当。您只需遵循动态元素模式。算出由于浏览器的不同,当加载脚本时会有一点棘手:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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模式,作者Stoyan Stefanov(奥赖利)版权所有2010 Yahoo!公司,9780596806750。"
您只需通过javascript生成脚本标记并将其添加到文档中。
1 2 3 4 5 6 7 8 9 10 11 | 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'>"); } } |
我使用了Tangim响应,但在发现这是更容易使用的jquery html()函数之后。当我们向具有html+javascript的html文件发出Ajax请求时,我们执行以下操作:
1 2 3 4 5 6 | $.ajax({ url:'file.html', success:function(data){ $("#id_div").html(data); //Here automatically load script if html contain } }); |
我想你是在为这个而乐吧http://unixpapa.com/js/dyna.html
1 2 3 4 5 6 7 8 9 10 11 | <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); } |