验证外部脚本加载 [英] Verify External Script Is Loaded

查看:126
本文介绍了验证外部脚本加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个jQuery插件,我想验证一个外部脚本被加载。这是一个内部Web应用程序,我可以保持脚本名称/位置一致(mysscript.js)。这也是一个ajaxy插件,可以在网页上多次调用。

I'm creating a jquery plugin and I want to verify an external script is loaded. This is for an internal web app and I can keep the script name/location consistent(mysscript.js). This is also an ajaxy plugin that can be called on many times on the page.

如果我可以验证脚本没有加载,我会使用加载它:

If I can verify the script is not loaded I'll load it using:

jQuery.getScript()

如何我可以验证脚本被加载,因为我不希望加载的页面上不止一次相同的脚本?这是不是说我不应该需要担心,由于剧本的缓存?

更新:
我可能没有对谁在我们的组织使用这个插件控制可能无法执行该脚本是不是已经有或无特定ID在页面上,但脚本的名称总是会在与同一样的地方名称。我希望我可以使用脚本的名称,以验证它的实际加载。

Update: I may not have control over who uses this plugin in our organization and may not be able to enforce that the script is not already on the page with or without a specific ID, but the script name will always be in the same place with the same name. I'm hoping I can use the name of the script to verify it's actually loaded.

推荐答案

如果该脚本会在全局空间您可以检查自己的所有脑干任何变量或函数:

If the script creates any variables or functions in the global space you can check for their existance:

JS外(在全球范围内) -

External JS (in global scope) --

var myCustomFlag = true;

和检查,如果这已经运行:

And to check if this has run:

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

更新

您可以检查&LT的存在;脚本&GT; 通过选择所有的标签有问题的&LT;脚本&GT; 元素,并检查他们的的src 属性:

Update

You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}

您也可以直接烤这个 .filter()功能直接进入选择:

var len = $('script[src="<external JS>"]').length;

这篇关于验证外部脚本加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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