Domanda

We have some code that needs to access values from _spPageContextInfo. The problem is that our Custom.js file is loaded before the information is available/defined.

We put the following code at the end of our Custom.js, which waits until sp.js is loaded and SP.ClientContext has executed.

SP.SOD.registerSod('sp.js', '_layouts/15/sp.js');
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function() {
    Custom.init();
    SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('custom.js');
});

This works if sp.js isn't loaded. But if sp.js has already loaded by the time this code is run then nothing happens.

So then we would use this which takes care of both cases -- sp.js is already loaded or sp.js is yet to load.

SP.SOD.registerSod('sp.js', '_layouts/15/sp.js');

// if it isn't already loaded wait until it is loaded
SP.SOD.executeOrDelayUntilScriptLoaded(function(){
    Custom.init();
    SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('custom.js');
}, "sp.js"); 

// load file if it isn't already loaded otherwise do nothing
SP.SOD.executeFunc("sp.js", null, null);

This type of construction, relying on both executeFunc and executeOrDelayUntilScriptLoaded, has worked for us in the past. The problem now is that sp.js loads and the code inside executeOrDelayUntilScriptLoaded runs before SP.ClientContext has executed.

Is there a way to use executeOrDelayUntilScriptLoaded like executeFunc, that is, to wait until a function in the referenced script is complete?

Or is there a better way to wait until _spPageContextInfo is defined before executing our code?

È stato utile?

Soluzione

I have done it like this in the past:

(function() { 
    var waitForPageContext = setInterval(function(){ 
        if(typeof _spPageContextInfo === "object") {
            clearInterval(waitForPageContext);
            Custom.init();
        }
    },100);
})();

Havent found a better solution, works great tbh.

You could notify it if you are using it other places too, something like this:

(function() { 
    var waitForPageContext = setInterval(function(){ 
        if(typeof _spPageContextInfo === "object") {
            clearInterval(waitForPageContext);
            NotifyScriptLoadedAndExecuteWaitingJobs("pagecontext");
        }
    },100);
})();

ExecuteOrDelayUntilScriptLoaded( function() { 
    Custom.init(); 
}, "pagecontext");

ExecuteOrDelayUntilScriptLoaded( function() { 
    // some other stuff etc
}, "pagecontext");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top