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.

如果我可以验证脚本是否未加载,我将使用以下方法加载它:

jQuery.getScript()

How can I verify the script is loaded because I don't want the same script loaded on the page more than once? Is this something that I shouldn't need to worry about due to caching of the script?

更新: 在我们的组织中,我可能无法控制谁使用此插件,也可能无法强制该脚本不在页面上,无论是否具有特定ID,但脚本名称将始终位于相同的位置,具有相同的名称.我希望我可以使用脚本的名称来验证它是否已实际加载.

推荐答案

如果脚本在全局空间中创建了任何变量或函数,您可以判断它们是否存在:

外部JS(在全局)--

var myCustomFlag = true;

并判断是否已运行:

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

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>');
}

Or you can just bake this .filter() functionality right into the selector:

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

Jquery相关问答推荐

在添加_renderMenu方法时,是什么原因导致jQuery UI AutoComplete抛出TypeError?

即使我使用 [FromBody] C# 从视图(Ajax)发送请求时在控制器中收到 NULL 对象

Flask,如何为ajax调用返回成功状态码

什么是不使用 jQuery 的经验技术原因?

jQuery 滚动到 Div

调用 jquery ajax - .fail vs. :error

jQuery JSON到字符串?

如何在 Backbone.js - Backbone.sync 或 jQuery.ajax 中保存整个集合?

如何获取文档的滚动位置?

如何使div全屏?

scrollIntoView 是否适用于所有浏览器?

动画元素变换旋转

jquery beforeunload 关闭(不离开)页面时?

如何使用 jQuery 更改文本

JQuery Ajax Post 导致 500 内部服务器错误

类方法中的Typescript this

jQuery表格行中的每个循环

如何将参数传递给 jQuery 中的事件处理程序?

在jQuery中获取CSS规则的百分比值

使用 Chosen 插件更改 Select 中的 Select