Some jQuery functions only works in Edit Page mode, not when the page is published

This is a known issue for publishing pages has become a common problem in SharePoint Development. Some Javascript libraries are not loaded in SharePoint page Publishing mode. For an example, as a part of Minimal Download Strategy(MDS), “sp.js” may not be loaded at every page load, unless it is explicitly loaded.

Thus, some jQuery features may not work in the following code in Publishing pages,

$(document).ready(function() {

// My custom functionality

});

Use the following code block instead;

$(document).ready(function ()

{

SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, myFunction);

});

function myFunction ()

{

// My custom code

};

“SOD.executeFunc” loads the “sp.js” file first and then execute the custom functions

The problem we have with exectueFunc is, if the script associated with the script key is already loaded, then executeFunc does absolutely NOTHING. In our case, if “sp.js” is already loaded, “myFunction” will not be executed. Thus, if you use your code in a button click function, button click code will only be executed once.

To get our function executed all the time, we have to use both methods in conjunction with one another as follows:

executeOrDelayUntilScriptLoaded(function() {

..My Code..

},”custScript.js”);

executeFunc(“custScript.js”, null, null);

Above code will queue “My Code”, until “custScript.js” is loaded. If “custScript.js” is already loaded, it will execute “My Code” straight away.

Different between document.ready vs spBodyOnLoadFunctions

SharePoint uses its own body onload function called, _spBodyOnLoadFunctionNames. It is recommended to use this as it allows the things to load in their proper order.

In some cases, you might need to execute your jQuery code after the page is completely loaded. For example; if you want to re-write / overwrite page elements/tags, use the following code segment;

_spBodyOnLoadFunctions.push(function(){

ExecuteOrDelayUntilScriptLoaded(myFunction, “sp.js”);

});

function myFunction ()

{

};