Sharepoint - Javascript to display sharepoint list items on page load

The reason why you get the SP.ClientContext is null or not an object error is because when you call your function on window.onload event, the sp.js file is not loaded on the page yet. The sp.js file contains all the code for the Client Object Model and hence your code is not able to find the SP.ClientContext object.

The solution is pretty simple. Call you function like this:

<script type="text/javascript">
  window.onload = function(){ ExecuteOrDelayUntilScriptLoaded(ViewItem, "sp.js"); };
</script>

The ExecuteOrDelayUntilScriptLoaded function makes it sure that your ViewItem function is executed only after the sp.js file is completely loaded on the page.


The accepted (working) solution is as by the comments jQuery:

$(document).ready(function(){ ExecuteOrDelayUntilScriptLoaded(ViewItem, "sp.js"); });

SharePoint 2010 introduces new feature named Script On Demand. It means that almost all scripts in sharepoint loaded on demand. In your situation you access to SP.ClientContext that is declared in sp.js, which is not loaded yet. Special function exists to wait until particular js file is loaded - ExecuteOrDelayUntilScriptLoaded. This function accepts two arguments - function and script name. If script with specified name already loaded, function will be called immediately, if not, it will be called as soon as script will be loaded.

Your code using this notes should look like:

window.onload = function(){
    ExecuteOrDelayUntilScriptLoaded(ViewItem, "sp.js");
}

And some more notes. If you want to run some js code after page load, preferable way to use shaerpoint built-in mechanism (or jQuery if possible) which involves using _spBodyOnLoadFunctionNames array. This array contains function names that will be called after body loaded. So, updated code:

function myfunc(){
  ExecuteOrDelayUntilScriptLoaded(ViewItem, "sp.js");
}
_spBodyOnLoadFunctionNames.push("myfunc");

Tags:

Javascript