SharePoint JavaScript Client Object Model: How to Use
_spBodyOnLoadFunctionNames.push
ExecuteOrDelayUntilScriptLoaded
SP.ClientRuntimeContext.executeQueryAsync
This is a blog that discusses when and how to use these important SharePoint Javascript calls.
1. _spBodyOnLoadFunctionNames.push() is SharePoint's version of jQuery's $(document).ready() or $(function(){});
It is better to use SharePoint's version than using jQuery's version.
2. _spBodyOnLoadFunctionNames.push() takes the function names as string,
For example, for self-defined function use
_spBodyOnLoadFunctionNames.push('Company.Utility.hideText');
Since the function name passed as string, it is not possible to pass parameters to the function directly. The parameters have to be passed inside the function itself.
3. If your Javascript use SharePoint Client Object Model, you need to use ExecuteOrDelayUntilScriptLoaded to delay your Client Object calls after SharePoint's core Javascript library is loaded. The function name is passed directly as parameter to the function.
ExecuteOrDelayUntilScriptLoaded(Company.Utility.showData, "sp.js")
4. To pass parameters to the function calls deplayed by ExecuteOrDelayUntilScriptLoaded.
ExecuteOrDelayUntilScriptLoaded(function () { Company.ReportListView.initListView("<%=ReportName %>") }, "sp.js")
This code also shows the technique to pass server side variable value to the client script.
5. Usually you will need these two functions together to first delay the run of your script after the page is loaded and delay the run of your script after the core SharePoint JavaScript library is loaded.
<script type="text/javascript"> if (ExecuteOrDelayUntilScriptLoaded && _spBodyOnLoadFunctionNames) { _spBodyOnLoadFunctionNames.push(ExecuteOrDelayUntilScriptLoaded(function () { Compnay.ReportListView.initListView("<%=ReportName %>") }, "sp.js")); } </script>
6. To pass parameter to the success function of SP.ClientRuntimeContext.executeQueryAsync
function initListView(reportName) { var context = SP.ClientContext.get_current(); ... context.load(items); var sender = { "items": items, "reportName": reportName }; context.executeQueryAsync(function () { succeed(sender); }, failed); }
function succeed(sender, args) { if (sender.items) { var htmlOutput = ""; var count = sender.items.get_count(); ...