使用javascript根据需要注入脚本引用? [英] Use javascript to inject script references as needed?

查看:114
本文介绍了使用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.

这是我的代码(Rev 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;
    }
}

以及带依赖关系的方法:

and in the method with a dependency:

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根据需要注入脚本引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆