Quick Tips: SharePoint and Dom Ready

If you're a front end developer working with SharePoint you likely already know about the multiple JavaScript and CSS files that get loaded before your code executes. The majority of this code is used to power the various admin tools that make up the SharePoint interface.

There are times you want to execute code at a specific point before your site content appears but after the DOM is ready. For example you might need SPservices to load so you can query a user ID. Or maybe you want to manipulate the S4-Workspace div before the SharePoint UI loads.

In cases such as these using DOM ready isn't reliable since you require your JavaScript resources to run after other JS files have been executed but before the page has loaded.

Luckily SharePoint provides a few options if you want more control over code execution. Here are three ways to specify the sequence in which your code runs.

If you want to be certain your code is firing last, once all SharePoint resources have loaded, you can use the following example.


function myCustomFuction(){
	 // Any code you want here...
}
_spBodyOnLoadFunctionNames.push('myCustomFuction');

In other cases you might know where in the sequence of files you want your JS to fire. For example you might want to modify the S4 Workspace div after it's loaded. Let's assume there's a js file called s4workspace.js (completely fictional name). This file is part of SharePoint and you want to run your code after that file has loaded and executed. You can specify the file by name like so.


function myCustomFuction(){
	 // Any code you want here...
}
ExecuteOrDelayUntilScriptLoaded(myCustomFuction, "s4workspace.js");

The last example is similar to the second, in this case however we don't want to wait for the file to execute. We just want to run the file as soon as a specific file has loaded in memory.


function myCustomFuction(){
	 // Any code you want here...
}
SP.SOD.executeFunc("s4workspace.js");

About the Blog

A funny thing happened when I started my design career, I fell in love with code. Many years later I now find myself working primarily doing front end development but I also occasionally work with backend tech.

This blog is a collection of my thoughts and what I'm working with at any given moment. It's a work in progress, so if you spot an error or have a comment please share!

Archive