验证外部脚本已加载 [英] Verify External Script Is Loaded
问题描述
我正在创建一个 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;
并检查它是否已运行:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
更新
您可以通过选择所有 元素并检查它们的
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()
功能烘焙到选择器中:
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
这篇关于验证外部脚本已加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!