As you may notice from today’s posts, I have spent last few weeks working with JSOM in SharePoint publishing pages. One of the main requirement was calling JavaScript methods to initialize page controls and validating page components while SharePoint publishing pages gets loaded in edit mode.
There are couple of options available while working with JavaScript CSOM to invoke JavaScript methods during Page Load.
Option 1 => ExecuteOrDelayUntilScriptLoaded Method
http://msdn.microsoft.com/en-us/library/ff411788(v=office.14).aspx
This method is part of SharePoint client side JS library and executes the specified function if the file containing it is loaded; otherwise, adds it to the pending job queue.
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server"> <SharePointWebControls:scriptlink id="SPScriptLink" language="javascript" name="sp.js" runat="server" LoadAfterUI="true" Localizable="false"/> <script type="text/javascript"> //Onload function function InitializePageCode(){ //main initialize code goes here… } </script> </asp:Content> <asp:Content ContentPlaceholderID="PlaceHolderMain" runat="server"> <script type="text/javascript"> //Invoke Onload handler after sp.js is loaded var e = ExecuteOrDelayUntilScriptLoaded(InitializePageCode, "sp.js"); </script> <div> Main page content goes here… </div> </asp:Content>
Option 2 => _spBodyOnLoadFunctionNames “push” Method
This object is part of SharePoint client side JS library and allows us “push” method to execute the specified function if the file containing it is loaded.
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server"> <SharePointWebControls:scriptlink id="SPScriptLink" language="javascript" name="sp.js" runat="server" LoadAfterUI="true" Localizable="false"/> <script type="text/javascript"> //Invoke Onload handler _spBodyOnLoadFunctionNames.push("InitializePageCode"); //Onload function function InitializePageCode(){ //main initialize code goes here… } </script> </asp:Content> <asp:Content ContentPlaceholderID="PlaceHolderMain" runat="server"> <div> Main page content goes here… </div> </asp:Content>
Hi Nik, where i should use the code you provide? in the masterpage head section I guess?
No, I usually use it in the page itself.. Either insert JavaScript block or separate JavaScript file.. I usually avoid adding business logic javascripts in master page..
Any alternative for SetInterval in sharepoint 2013