Javascript on sharepoint page load: spBodyOnLoadFunctionNames.push( ) vs image onload( )

So you want to start customizing a SharePoint page? Let’s say, you want to load or hide something in a page.
First steps include adding a content-editor-webpart on the page and adding some code on the source editor:

<script language="javascript">

function FunctionName(){
  // Custom JavaScript methods

SharePoint provides the “_spBodyOnLoadFunctionNames” array. When the body is loaded, the onload event handler executes each function whose name is contained in this array. “FunctionName” was added to the array so that it would run when the body’s onload event fires.

In the function you can put all javascript you want.
At a client, this function was not called. Very weird problem, but we got a workaround really quickly from this blog

Adding an empty image on the page, and using the onload event of the image to start your code:

<img src="/_layouts/images/blank.gif" width="1" height="18" />

SharePoint already provides you with the blank image by default. Just add this line to you content-editor-webpart and add your function in the script tags.

About: Marijn

Marijn Somers (MVP) has over 14 years experience in the SharePoint world, starting out with SP2007. Over the years the focus has grown to Office 365, with a focus on collaboration and document management. He is a business consultant at Balestra and Principal Content Provider for "Mijn 365 Coach" that offers dutch employee video training. His main work tracks are around user adoption, training and coaching and governance. He is also not afraid to dig deeper in the technicalities with PowerShell, adaptive cards or custom formatting in lists and libraries. You can listen to him on the biweekly "Office 365 Distilled" podcast.

4 thoughts on “Javascript on sharepoint page load: spBodyOnLoadFunctionNames.push( ) vs image onload( )”

  1. Thank You. This helped me to call a javascript function on sharepoint page.

    thank you very much

  2. I tried your solution using image to call a javascript function I have and it works fine on Firefox but it doesn’t work for me in IE or Chrome. What my javascript function does is to get the breadcrumb generated by Sharepoint and retrieve only the current page name from it. Could you help please?

    1. it doesn’t do the code ? Have you tried if it goes into the function ? (with something like a “hello world”)? you can always send me the code so I can take a look at it.

Leave a Reply

%d bloggers like this: