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

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

问题描述

我正在创建一个 jquery 插件,并且我想验证一个外部脚本是否已加载.这是一个内部网络应用程序,我可以保持脚本名称/位置一致(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>');
}

更新

您可以通过选择所有 <script> 元素并检查它们的 src<来检查相关

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