问题描述
我正在创建一个 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<来检查相关
标记是否存在/code> 属性:
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()
功能直接烘焙到选择器中:
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
这篇关于验证外部脚本是否已加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!