简体   繁体   English

如何检查某个 JS 文件是否包含在网页中?

[英]How to check if certain JS file was included in a webpage?

In my custom JS code file I use various plugins, for instance, the Masonry plugin for JQuery.在我的自定义 JS 代码文件中,我使用了各种插件,例如 JQuery 的 Masonry 插件。 However, I don't include the plugin on every page or at the master page file level (in some yes, in some no) but I do include my custom file on every page.但是,我没有在每个页面或母版页文件级别包含插件(在某些情况下是,在某些情况下不是),但我确实在每个页面上都包含我的自定义文件。 Therefore, the code in my JS file will issue an error if the Masonry plugin is missing.因此,如果缺少 Masonry 插件,我的 JS 文件中的代码会报错。

If someone could reply with a solution of how to:如果有人可以回答如何:

  1. Check if certain JS plugin was referenced (included) and only run the code then,检查是否引用了某些 JS 插件(包括),然后只运行代码,
  2. (optionally) include the file at runtime if it is missing. (可选)如果文件丢失,则在运行时包含该文件。

I have it working with JQuery and JQuery UI because they both introduce a class into DOM structu (jquery and jquery.ui objects) but there are other plugin's like lightbox scripts, the forementioned Masonry etc.. I have it working with JQuery and JQuery UI because they both introduce a class into DOM structu (jquery and jquery.ui objects) but there are other plugin's like lightbox scripts, the forementioned Masonry etc..

Rather than checking whether a particular JavaScript file has been 'included', I'd just check if the functionality that you need is available (ie if you need a function named foo , just do something along the lines of typeof foo == 'undefined' to see if it is there...).而不是检查特定的 JavaScript 文件是否已被“包含”,我只是检查您需要的功能是否可用(即,如果您需要一个名为foo的 function ,只需按照typeof foo == 'undefined'看看它是否在那里......)。

What you are trying to do is probably a bad idea, but anyway here's how to determine if a given plugin has been defined.您尝试做的可能是一个坏主意,但无论如何这里是如何确定是否已定义给定插件。 In jQuery they are just namespaces to the jQuery scope :在 jQuery 中,它们只是jQuery scope 的命名空间

if(!jQuery().somePlugin) {
    // the plugin is not loaded => load it:
    jQuery.getScript('/url_of_the_plugin', function() {
        // the plugin is now loaded => use it
    });
}

You can only check if its class or methods are defined, in your case:您只能检查其 class 或方法是否已定义,在您的情况下:

if (typeof($.fn.masonry) == 'undefined') ...

Anyway, I'll recommend including every script at every page, compressed into one file.无论如何,我建议在每个页面中包含每个脚本,并压缩到一个文件中。 The cost of downloading and parsing potentially not needed code is often far less than penalty of having multiple HTTP requests.下载和解析可能不需要的代码的成本通常远低于拥有多个 HTTP 请求的代价。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM