如何检查网页中是否包含某个JS文件?
在我的自定义 JS 代码文件中,我使用了各种插件,例如 JQuery 的 Masonry 插件。但是,我不会在每个页面或母版页文件级别上包含该插件(有些是,有些不是),但我确实在每个页面上都包含了我的自定义文件。因此,如果缺少 Masonry 插件,我的 JS 文件中的代码将发出错误。
如果有人可以回复如何解决以下问题:
- 检查是否引用(包含)某些 JS 插件,然后仅运行代码,
- (可选)如果文件丢失,则在运行时包含该文件。
我让它与 JQuery 和 JQuery UI 一起使用,因为它们都在 DOM 结构中引入了一个类(jquery 和 jquery.ui 对象),但还有其他插件,如灯箱脚本、前面提到的 Masonry 等。
In my custom JS code file I use various plugins, for instance, the Masonry plugin for JQuery. 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.
If someone could reply with a solution of how to:
- Check if certain JS plugin was referenced (included) and only run the code then,
- (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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不会检查某个特定的 JavaScript 文件是否已被“包含”,而只是检查您需要的功能是否可用(即,如果您需要一个名为
foo
的函数,只需执行以下操作即可typeof foo == 'undefined'
来查看它是否存在...)。Rather than checking whether a particular JavaScript file has been 'included', I'd just check if the functionality that you need is available (i.e. if you need a function named
foo
, just do something along the lines oftypeof foo == 'undefined'
to see if it is there ...).您尝试做的事情可能是一个坏主意,但无论如何,这里是如何确定给定插件是否已定义的方法。在 jQuery 中,它们只是 jQuery 范围的命名空间:
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:
在您的情况下,您只能检查其类或方法是否已定义:
无论如何,我建议在每一页上包含每个脚本,并将其压缩到一个文件中。下载和解析可能不需要的代码的成本通常远远低于多个 HTTP 请求的损失。
You can only check if its class or methods are defined, in your case:
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.