Thursday, September 18, 2014

ExecuteOrDelayUntilScriptLoaded with SP.JS

There was a survey that the management wanted to publish depending on the domain of the logged on user. Say if the user belongs to Asia and America, the system should popup a dialog for the survey. We decided to use JavaScript client object model to find the domain of the logged on user.

We used the following code on the home page which already had some JavaScript menus.

ExecuteOrDelayUntilScriptLoaded(init, "sp.js");

function init() 
{
            this.clientContext = new SP.ClientContext.get_current();
            this.oWeb = clientContext.get_web();
            currentUser = this.oWeb.get_currentUser();
            this.clientContext.load(currentUser);
            this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    
}

After applying this code the JavaScript menus were not coming up. So checked the code and found that ExecuteOrDelayUntilScriptLoaded has to be used with a function name. Hence changed the code like below and JavaScript menus started coming up.

jQuery(document).ready(function() {
 ExecuteOrDelayUntilScriptLoaded(init, "sp.js");
});
       
  //      ExecuteOrDelayUntilScriptLoaded(init, "sp.js");
         function init() {
            this.clientContext = new SP.ClientContext.get_current();
            this.oWeb = clientContext.get_web();
            currentUser = this.oWeb.get_currentUser();
            this.clientContext.load(currentUser);
            this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
   
        }

Hope this helps you!!!



No comments:

Post a Comment