Thursday, July 05, 2007

Adding JavaScript to a Content Editor Web Part to Run onLoad

Adding JavaScript to a page inside a Content Editor web part can be a great way to perform on-the-fly customizations to your SharePoint sites. This worked great in WSS v2 and SPS 2003. We started noticing that some of those scripts didn’t seem to work in WSS v3 and MOSS 2007, however, and it wasn’t because the names of objects and elements had changed.
For example, here is a JavaScript snippet that we had used to hide the “NEW!” icon on a page in WSS v2.Note: In all code examples below, replace the square brackets around the SCRIPT tags with angle brackets. If I included the angle brackets, the browser tried to execute the code. :o(

When we added this to a Content Editor web part in a WSS v3 page, nothing seemed to happen. I added code to make it run on the onLoad event, and that didn’t work either. I did a little experimentation and discovered that if I added a short delay, even a delay of 1/1000 of a second, it worked fine. I placed the core code within a function and then called it with the setTimeout() method.

The problem occurs because most WSS v3 pages use a master page that contains the “body” element, and the page content code loads after the master page code. I didn’t know it at the time, but recently discovered (thanks to this article on the Microsoft SharePoint Products and Technologies Team Blog) that the SharePoint developers had given us a way to work around that issue—it’s the _spBodyOnLoadFunctionNames array. We can use JavaScript’s “push” method to load items into this array where they will run when the body’s onLoad event fires .
Here is what the JavaScript looks like with the setTimeout replaced with a line that pushes the function name “HideNewIcons” into the _spBodyOnLoadFunctionNames array.

If you’ve been having trouble getting some of your legacy JavaScript scripts to run from within Content Editor web parts in WSS v3 or MOSS 2007 pages, give this technique a try, and let me know if it works for you.