Referencing JavaScript files from a CDN in a CRM 2011 form


UPDATE: I’ve changed the approach in this post because the original code has some side effects where it doesn’t always load correctly, plus I discovered RequireJS.

I’m a big fan of referencing JavaScript files from a Content Delivery Network (CDN) when it makes sense.  Why?  I think the Microsoft Ajax CDN site does a good job of explaining things:

http://www.asp.net/ajaxlibrary/cdn.ashx

“The Microsoft Ajax Content Delivery Network (CDN) hosts popular third party JavaScript libraries such as jQuery and enables you to easily add them to your Web applications. For example, you can start using jQuery which is hosted on this CDN simply by adding a <script> tag to your page that points to ajax.aspnetcdn.com.

By taking advantage of the CDN, you can significantly improve

the performance of your Ajax applications. The contents of the CDN are cached on servers located around the world. In addition, the CDN enables browsers to reuse cached third party JavaScript files for web sites that are located in different domains.”

It may not be obvious at first, but you can do this within your CRM 2011 solutions as well.  CAVEAT: This might fall into the “don’t muck with our DOM” mantra of CRM development…I can’t guarantee this is an officially supported scenario.  But as they say, it works and the risk is pretty low.

Please read my Using RequireJS with CRM 2011 forms post.  Once you have the following web resource code should make sense:

function dkdt_referencejQueryFromCDN() {    
    // Check to see if jQuery is already loaded
    // If not, then load it
    if (typeof jQuery == 'undefined') {
        // NOTE: use https if your CRM deployment is running under https
        require(["http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js", function (m) {
            // Do what you would normally do after the file was loaded
        });                
    }
}

Add require.js followed by the web resource that contains the code above to the form.  Wire up the Form OnLoad to call the function in your web resource:

image

BAM!  You have a just referenced a CDN based JavaScript file.  You now have all the benefits that a CDN reference offers.

@devkeydet

Comments (0)

Skip to main content