Fri. Nov 22nd, 2019

Samir Daoudi's Technical Blog

SharePoint, Office 365, C#, .Net, SQL Server News, Tips, Ebooks, Events, Webinars ….etc

SP.JS – Loading and timing issues

In this post, I will share with you guys my experience with SP.JS.

First of all, I felt in love with SP.JS when I could do literally any CRUD operation from the browser.

Donโ€™t get me wrong, coming from C#.Net background to SP.JS took some time to familiarise myself with different topics of this last. Finally, I arrived to the conclusion, that I love SP.JS (once I got myself comfortable with it).

The first issue I had with SP.JS, was the fact that I did not have any control on the load order of the scripts, so I had to make sure that all my JavaScript code would wait for SP.JS to Load. For this, I used the following line of code

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
function sharePointReady() {
var clientContext = new SP.ClientContext();
// my code goes here
}

This was perfect, from the sharePointReady function, I could do pretty much anything, I re-used it in different projects, and believe me, the final results was very Wowing ๐Ÿ™‚

PS: This was experienced in a Sharepoint On-Prem environment.

ย 

I had to migrate one of my project to SharePoint Online (Office365), and suddenly this script was not doing what I thought I have fixed in the past.

The SP.JS was running before the DOM finished loading. I noticed different behaviours when I refreshed the page (F5), or just select the URL (and hit enter).

If my script was updating any DOM object (which was the case in most of the cases), I had issues.

The solution was to do the check of SP.JS and call the sharePointReady function from the document.ready() function.

$(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
        });

        function sharePointReady() {
            var clientContext = new SP.ClientContext();
// My code goes here
}

ย 

Leave a comment

Show Buttons
Hide Buttons
%d bloggers like this: