1

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?

1

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");
  • Thanks for the idea of using a timer. Guess sometimes you just have to go around the SP system! Seems like they should have a way to make that work. – Rothrock Jun 7 '18 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.