Tuesday, April 21, 2015

_SPBODYONLOADFUNCTIONNAMES IN SHAREPOINT VS. JQUERY’S DOCUMENT READY

Copyright from: www.stephanrocks.com

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!

No comments: