根据需要使用 javascript 注入脚本引用?

2022-01-25 00:00:00 include 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.

相关文章