Search This Blog

Saturday, July 29, 2017

SP.js not load on Sharepoint Pages or Loading/ensuring JavaScript files


There is an issue I found when working on Sharepoint 2013. I got “SP.js” error right after 
published the page and cause some feature disable, such as ribbon and other scripts can
 not be executed. It seems that SP.js does not load properly for publishing page and 
anonymous users. Some articles said that sharepoint loads certain javascript files when
 it needs, after published the page, ribbon will close and several javasripts were unload 
automatically.
Actually Sharepoint provides some methods to call scripts for many conditions. So we 
could choose wisely among them to solved our problem. Take a look :
1) Script on Demand.
1
2
3
4
function sharePointReady(){
    // call this code after load SP.js
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
2) Delay until SP.js loaded.
1
2
3
4
function stuffToRun(){
   // code
}
ExecuteOrDelayUntilScriptLoaded(stuffToRun, "sp.js")




The different between 1 and 2:
SP.SOD.executeFunc(key, functionName, fn) method ensures that the specified file (key) 
that contains the specified function (functionName) is loaded and then runs the specified
 callback function (fn). Use case for “SP.SOD.executeFunc” can be that at some point you
 wish a JavaScript library like JQuery be loaded before you call a function defined inside it
 via callback function.
SP.SOD.executeOrDelayUntilScriptLoaded(func, depScriptFileName) method executes the
 specified function (func) if the file (depScriptFileName) containing it is loaded; otherwise, 
adds it to the pending job queue.
3) Load after other stuff finished.
1
2
3
4
function runAfterEverythingElse(){
    // code
}
_spBodyOnLoadFunctionNames.push("runAfterEverythingElse");





SharePoint JavaScript Library, in particular SP.SOD namespace contains methods for loading/
ensuring JavaScript files.
1.      SP.SOD.executeOrDelayUntilScriptLoaded - executes the specified function if the file containing 
it is loaded, for example:
2.  ExecuteOrDelayUntilScriptLoaded(myfunc, "SP.js");
3.        
4.       function myfunc()
5.       {
}
In that case myfunc will be invoked after sp.js file is loaded
6.      SP.SOD.executeFunc - ensures that the specified file that contains the specified function is loaded 
and then runs the specified callback function, for example:
7.  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', 
8.        function (){
9.            //your code goes here...
 });
The behavior is similar to previous example but the main difference that this function also supports
 load on demand scripts.

3-If SP.js is Not Load
 Then  For User  Profile
  
$(window).load(function(){
     SP.SOD.executeFunc('sp.js', 'SP.ClientContext',init);
});

No comments:

Post a Comment