_spBodyOnLoadFunctionNames in SharePoint vs. jQuery’s document ready

In the last few months, I’ve done a lot of integration of jQuery into SharePoint for its rich animation framework.  Instantiating the jQuery has always been an interesting challenge.  During the branding process and masterpage creation, everything seems to work great.  As time goes on and more content is added, different site types are used, etc., you can run into some interesting behaviors ranging from $ collisions and scripts not loading at all.

Follow these 2 simple rules to use jQuery in harmony with SharePoint:

Set jQuery to its no-conflict state.

This requires you to use jQuery instead of $

example:

$("#element > span").text("my text");

becomes

jQuery("#element > span").text("my text");

Use SharePoint’s _spBodyOnLoadFunctionNames array instead of jQuery’s document ready function

Why not you ask?  SharePoint uses its own body onload function called _spBodyOnLoadFunctionNames which will collide with your document ready (run before or after).  If you are loading your JavaScript files through the elements.xml file (through a feature in Visual Studio), this can be particularly problematic with the order of how things load.

Instead, create a function with a custom name, and push the custom name into the _spBodyOnLoadFunctionNames array.  It’s wonderful and allows things to load in their proper order.

So – with examples, instead of:

$(document).ready(function() {
     // My custom functionality
});
use:
_spBodyOnLoadFunctionNames.push("myCustomFunctionName");
function myCustomFunctionName() {
     // My custom functionality
}

That’s it.  Enjoy!

Written by

SharePoint Developer, Musician, Actor, Fool, Inventor, Crazyman, Geek ;-D

2 Comments to “_spBodyOnLoadFunctionNames in SharePoint vs. jQuery’s document ready”

  1. tomc says:

    Thanks. This saved me a ton of time. One question. from a jQuery novice: Is there any performance difference between $(…) and JQuery(…)? Thanks again.

    • stephan says:

      Hi tomc,

      From my knowledge there is no performance difference between using $(…) or jQuery(…). I prefer using jQuery(…) purely to prevent code conflicts. A few JavaScript libraries out there all use $(…), which in some cases can override each others’ functions/methods and cause a mess for you (this is a common occurance in some SharePoint sites).

      If you use jQuery.noConflict();, you ensure that jQuery is running in a mode where it is in its own namespace and will not mess with other libraries running on the same page (as you’re aware I’m sure – using jQuery.noConflict will render $(…) non-functional).

      I’m really glad you found some value in my blog. I love to share my knowledge and enjoy helping out the community! Thanks for the kind words. :)

      Stephan

Leave a Reply

Message

*