Friday 3 October 2014

SharePoint Online: ensuring sp.js (or any other scrip library) is loaded

Load By Sod to the rescue!


Came across a nice gotcha this afternoon whilst trying to diagnose why some javascript in a content editor wasn't firing correctly on system settings pages (it's a terms and conditions agreement pop-up dialogue that must display the first time a user hits the site whatever their entry page).


Basically, I was being a dutiful defensive developer (try saying that three times fast after a few Friday afternoon vodkas! ;) and making sure that I wasn't attempting to use any of the built in sp.js functions before they were loaded. So not only had I wrapped my initialisation scripts inside the standard jquery document ready 'wait' but also used ExecuteOrDelayUntilScriptLoaded to make sure sp.js was present before any of my follow on code processed.

The problem


This worked fine on every page except system settings and pages akin to that. The content was being written quite correctly to the output html, the javascript was all there, but nothing was firing. In the end of course I worked out that this particular type of page *never* loads sp.js and so my scripts were never actually firing. I guess I should applaud MSFT for not loading unnecessary js libraries, but it's Friday I don't want to have to deal with this nonsense.

The solution


The solution is to take a slightly different approach to checking whether the script is loaded correctly or not on any page you place that kind of script and forcing it to load (using the correct SOD approach rather than dumping script tags all over the place as some folks recommend) if it isn't already going to be loaded by the page:

if (!SP.SOD.executeOrDelayUntilScriptLoaded (initialiseModalDialogue, 'sp.js')){ LoadSodByKey('sp.js'); };

What this script snippet does is the usual ExecuteOrDelay... with the function it should execute when it does (in this case 'initialiseModalDialogue'), but then when this fails it makes a LoadSodByKey call to force the script to be loaded and then falls back to making the function call.

A nice solution to a potential pita gotcha. Not bad for a Friday ;-)

- rob

No comments:

Post a Comment