简体   繁体   English

检查javascript lib是否已经存在

[英]Check whether javascript lib already exist

Can i check whether if my javascript ext-lib such as fancybox plugin have already existed in my page(don't matter its version)? 我可以检查我的页面中是否已经存在我的javascript ext-lib(例如fancybox插件)(无关版本)? I use liferay portlet, it can be place two same portlet in one page, I am already have some script confict now. 我使用liferay portlet,它可以将两个相同的portlet放在一页中,现在我已经有一些脚本冲突了。 (Liferay AUI script on layout configuration panel, slider in some assetPublisher ...) (布局配置面板上的Liferay AUI脚本,一些assetPublisher中的滑块...)

If you are testing for native javascript functions (ie built–in or created using javascript), then: 如果要测试本机javascript函数(即内置的或使用javascript创建的),则:

if (typeof foo == 'function')

will always work, regardless of which library you are using. 无论您使用哪个库,它都将始终有效。 eg to test if jQuery is available: 例如测试jQuery是否可用:

if (typeof jQuery == 'function')

I would not trust the jQuery isFunction method for host objects, and if you aren't testing host objects, typeof is completely reliable. 我不相信用于宿主对象的jQuery isFunction方法,如果您不测试宿主对象,则typeof是完全可靠的。

Edit 编辑

Oh, I should add that if you are testing methods of host objects, there are many aspects to consider. 哦,我还要补充一点,如果要测试主机对象的方法,则需要考虑许多方面。 The following is sufficient in the vast majority of cases: 在大多数情况下,以下内容已足够:

if (hostObject && hostObject.method) {
  // call hostObject.method
}

It's worth noting that host objects aren't required to comply with ECMA-262 (though most modern implementations do to a large extent, at least for DOM objects). 值得注意的是,不需要宿主对象符合ECMA-262(尽管大多数现代实现在很大程度上都可以做到,至少对于DOM对象而言)。 There are a number of implementations in use that have host objects that, when tested with typeof will return “unknown” or similar, some older ones even threw errors. 许多使用主机对象的实现在使用typeof进行测试时将返回“未知”或类似结果,一些较旧的实现甚至抛出错误。

Some host objects throw errors if tested with object.prototype.toString.call(hostObject) (which jQuery's isFunction function uses), so unless you are going to implement a robust isHostMethod function, the above will do in the vast majority of cases. 如果使用object.prototype.toString.call(hostObject) (jQuery的isFunction函数使用)进行测试,则某些宿主对象会引发错误,因此,除非您要实现强大的isHostMethod函数,否则上述情况将在大多数情况下发生。

To check if a generic JS lib is loaded (aka not a jQuery plugin) test one of its functions: 要检查是否已加载通用JS库(又名jQuery插件),请测试其功能之一:

if ($.isFunction(pluginFunction)) {
    // Code to run if generic library is loaded
}

To check if a jQuery plugin is loaded: 要检查是否已加载jQuery插件:

if (jQuery().pluginName) {
    // Code to run if plugin is loaded
}

Hope this helps! 希望这可以帮助!

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

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