jQuery and jQuery UI with Dynamics CRM 2011 & 2013

Since I’ve been converting Silverlight web resources over to Html & JavaScript and working on www.SparkleXrm.com , I’ve worked extensively with jQuery and jQuery-UI.

In the early days of Dynamics CRM 2011, you could use both these libraries without a problem, but with the Activity Feeds solution an instance of jQuery appeared that interfered with your custom scripts.
This is still the case in Dynamics CRM 2013 and so here are some simple steps to ensure your libraries are safe and will co-exist with other instances from other solutions.

1. Decide on a custom ‘namespace’ for your jQuery library. I am using ‘xrmjQuery’

2. On the end of your jquery.js script add the following line:

/* jQuery script goes here */
window.xrmjQuery = jQuery.noConflict(true);

3. Inside your jquery_ui.js script (notice the ‘-‘ has been changed to an underscore since CRM doesn’t allow them in web resource names), wrap the whole file in the following lines:

(function ($,jQuery) {
    /*! jQuery UI Goes here */
})(window.xrmjQuery,window.xrmjQuery);

4. Inside your JavaScript web resource that use jQuery and jQuery-UI, wrap your code in the following:

(function($){
// Your Javascript goes here and can reference $ as usual
// e.g. var someField = $('#fieldName');
})(window.xrmjQuery);

This technique is called encapsulation and namespacing of jQuery.

My friend Carsten also has a blog post on a similar theme.

www.SparkleXrm.com uses the same technique and namespace is also ‘xrmjQuery’, so if you would like to quickly get access to the jQuery libraries in Dynamics CRM, you can install the SparkelXrm managed solution and include the web resource named ‘sparkle_/js/SparkleXrmUI_Dependancies.js’ – this is a single library that has both jQuery, jQueryUI as well as a few other goodies such as Knockout JS!

 

@ScottDurow

Comments (1) -

  • Hi Scott,

    Great post about a way to address conflicting objects names in scripts.  I've been using RequireJs for a while now to address this issue and a number of other ones.  I think you might find it easier to use a library like RequireJs for you dependency injection and dependency mapping.  It’s the later feature that allows for using multiple version of a library/module within a single project.  If you’re interested you can read more about this feature of RequireJs at

    http://requirejs.org/docs/api.html#multiversion
    http://requirejs.org/docs/api.html#config

    Either way, great post on a method to addressing the jQuery conflict issue. Oh one last thing, thank you for the quick turn around on getting the Ribbon Workbench updated for CRM 2013.
Comments are closed