How to load jQuery from within your DotNetNuke module safely

If you are writing a module for DotNetNuke that depends on jQuery, you must find a reliable way to make sure jQuery is loaded. Furthermore, you must make sure the right version of jQuery is loaded and must also ensure the rest of the DNN installation is not affected. Here is how you can do that.

Goals:

1. Detect whether jQuery is installed

2. Determine whether the right version of jQuery is installed. I will use 1.4.2 as my base.

3. Make sure to not cause conflict with other libraries that might be using the $ variable

 

Code:

<script type=”text/javascript”>

    // Check whether jquery 1.4.2 or greater is loaded
    var loadJQuery = (typeof (jQuery) == 'undefined' || 
                jQuery().jquery < "1.4.2");

    // Add a marker to invoke no conflict when the $ 
    //    is mapped to a library other than jQuery
    var callNoConflict = (typeof ($) != 'undefined' 
                && typeof (jQuery) == 'undefined')

    if (loadJQuery) {

        var filename= ‘your path to the jquery file’;
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
        document.getElementsByTagName("head")[0].appendChild(fileref);

    }

    if (callNoConflict) {
        jQuery(function(){
            jQuery.noConflict();
        });
    }

</script>

 

Will Strohl has put together a great article on the best practices for using jQuery within DNN

About these ads

3 responses to this post.

  1. Have you found any code or UI latencies, using this method?

    Reply

    • Hi Will

      I can see how this might have a tiny perf hit compared to just including the ref directly in the head element. However there is no other reliable way to load it when dealing with dnn4.x. DNN 5 and above this is not as much of a problem as you can pretty much rely on the framework.

      Mitch

  2. This is a nice script! We have run into this issue a number of times.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: