Wednesday, October 8, 2014

Developing SharePoint Visual Webparts: How to check if jQuery exist or is already loaded

When you try to create a SharePoint visual webpart that makes use of jQuery, it is generally known that any conflict will cause the javascript rendering to fail, e.g. any document.ready() function.

It is common when you have a lot of customized components that were activated as a feature.

You can easily check whether you have loaded conflicting versions of jQuery from viewing the source on the web page. But how do you control whether or not to load the jQuery if it already exists?

Solution:
Check whether the jQuery object can be created, before loading the .js file using javascript.
if (typeof jQuery == 'undefined') {
            var jq = document.createElement('script'); jq.type = 'text/javascript';
            // Path to jquery.js file
            jq.src = '/_layouts/Test/jquery.min.js';
            document.getElementsByTagName('head')[0].appendChild(jq);
        }

No comments:

Related Posts Plugin for WordPress, Blogger...