Blog

Working safely with SharePoint client scripts


22 May, 2010

SharePoint 2010 uses a lot of client side scripts and have now many ways of making sure that this is executed without errors and hang-ups. The method ExecuteOrDelayuntilScriptLoaded makes sure that calls to a library is not executed until said library is loaded.

Example:

 1: ExecuteOrDelayUntilScriptLoaded(showModal, 











 2: "sp.js");











 3:  











 4: function showModal()











 5: {











 6:     SP.UI.ModalDialog.showModalDialog({











 7: url: "/Lists/Announcements/NewForm.aspx";











 8:     });











 9: }






This is excellent practice as we can then ensure that our script libraries are loaded properly without the need for the developer to worry about when it’s loaded. To ensure that this works, add the following call at the bottom of your .js file:

NotifyScriptLoadedAndExecuteWaitingJobs("my.custom.lib.js");

This will cause the queued scripts to execute.

Also, make sure to enable client-side script debugging using Visual Studio and add breakpoints as the libraries can be very hard to navigate.