I'm trying to get an element once page has been loaded. However when I put the code in window.onload = function () { my code };
it's not working, without window.onload
it get's the element. here's my code:
<script language='javascript' type='text/javascript'>
var itemId = 12;
var targetListItem;
var ref;
//with window.onload
window.onload = function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', runCode);
}
//without window.onload
//SP.SOD.executeFunc('sp.js', 'SP.ClientContext', runCode);
function runCode() {
var clientContext = new SP.ClientContext.get_current();
var targetList = clientContext.get_web().get_lists().getByTitle('Employees');
targetListItem = targetList.getItemById(itemId);
clientContext.load(targetListItem, 'Name');
clientContext.executeQueryAsync(onQuerySucceeded,onQueryFailed);
}
function onQuerySucceeded() {
ref = targetListItem.get_item('Name');
alert(ref)
}
function onQueryFailed(sender, args) {
alert('Error');
}
</script>
When I run the in window.onload
I get the error:
Request failed.
Error: Item does not exist. It may have been deleted by another user.
StackTrace: undefined
The item exists in the list.
Does anyone know why is it like that? Thanks.
EDIT
I've noticed that the code with window.onload
works when the page is in edit mode. The code breaks at line SP.SOD.executeFunc('sp.js', 'SP.ClientContext', runCode);
in windows.onload
.