[SalesForce] Page cannot use jQuery Plugin as it’s registered with $ from Sidebar component

This again and again is a reason why jQuery-based pages in my apps fail to render at some customers but not at all customers…

There must be a solution to this. Or at least others who share the pain 😉

Image my page using jQuery in the recommended way

<apex:page>
    ... 
    <apex:includeScript value="//anycdn/jquery.min.js" /> 
    <apex:includeScript value="//anycdn/jquery.plugin.min.js" />

    <script type="text/javascript">
        jQuery.noConflict();

        jQuery(document).ready(function() {
            jQuery("#id").pluginMethod();
        });
    </script>
</apex:page>

Now imagine there is a Sidebarcomponent contains Javascript code that registers another version of jQuery with the noconflict() call and using the default alias $.

Sidebar components seem to load faster and so a plugin sometimes is registering not in the jQuery I load in the same page but in the previously loaded jQuery from the Sidebar component.

My call to jQuery("#id").pluginMethod(); will fail in the Browser with a Javascript error

undefined is not a function

The screenshot from my Browsers console proves that the Dynatree plugin was NOT registered with jQuery in the same page but with the $ loaded in the sidebar component (this was proven by using sidebar="false" on the page tag).

I see no easy solution to this as my Script works properly and I cannot really change neither the sidebar Javascript code nor how a Plugin registered itself.

Best Answer

One hacky work-around would be to look for the instance of jQuery that the plugin is registered with:

<script type="text/javascript">
jQuery.noConflict();

jQuery(document).ready(function() {
    if (typeof jQuery.pluginMethod === 'function') {
        jQuery("#id").pluginMethod();
    } else if (typeof $.pluginMethod === 'function') {
        $("#id").pluginMethod();
    }
});
</script>
Related Topic