Use javascript to inject script references as needed?(根据需要使用 javascript 注入脚本引用?)
问题描述
我有一个 JS 函数,可能偶尔会在某些页面上使用.它依赖于另一个 JS 文件(swfObject.js),但我想避免在所有地方都包含这个文件,因为大多数时候这是一个浪费的请求.
I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.
相反,我想创建一个通用函数,可以根据需要将脚本引用注入页面 DOM,因此如果调用此函数,它将检查脚本,如果不存在,则加载它在.
Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.
我很确定这是可能的(而且我不会使用 document.write),但在我冒险进入未知领域之前,有没有人这样做过,如果有,有什么建议吗?
I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?
好的,我试过了,IE6和FF都可以,我还没有测试过其他浏览器.
Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.
这是我的代码(修订版 2.0,现在带有可选回调):
Here is my code (Rev 2.0, now with optional callbacks):
function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
在有依赖的方法中:
var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
calbackMethod();
有什么建议吗?
推荐答案
如果您使用的是更高级别的框架,例如 JQuery,您可以查看 $.getScript(url, callback)
功能.
If you're using a higher level framework such as JQuery, you could check out the $.getScript(url, callback)
function.
这篇关于根据需要使用 javascript 注入脚本引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据需要使用 javascript 注入脚本引用?
基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 我什么时候应该在导入时使用方括号 2022-01-01