1

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.onloadit 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.

4
  • Check whether there is item with ID= 12 existing in the list
    – Unnie
    Commented Jul 26, 2016 at 9:52
  • Yes, I have checked and the item exists there. Why would it then get the item if I'm running the code without window.onload? Commented Jul 26, 2016 at 10:00
  • The itemID is defined as a global object. I think that object is getting modified somehow. Try to alert the value before executing the query and make sure it remains 12. Commented Jul 26, 2016 at 10:35
  • @AmalHashim No that's not the case. I've also passed 12 straight in getItemById method. Had the same error. Commented Jul 26, 2016 at 11:09

2 Answers 2

3

Here's a small utility to attach properly to the SharePoint lifecycle.

You use it like this:

window.LifeCycleHelper.AttachToLoad(function(){ alert('Hello World'); }); 

Utility:

//use an IIFE to create a scope and dont dirty the global scope
(function (_) {
    // use strict to ensure we dont code stupid
    'use strict';

    var initHandlers = [];
    var initMDSHandlers = [];

    var ensureSharePoint = function (handler) {
        var sodLoaded = typeof (_v_dictSod) !== 'undefined' && _v_dictSod['sp.js'] != null && _v_dictSod['sp.js'].state === Sods.loaded;

        if (sodLoaded) {
            handler();
        } else {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { });
            SP.SOD.executeOrDelayUntilScriptLoaded(handler, 'sp.js');
        }
    };

    var initMDS = function () {
        for (var i = 0; i < initMDSHandlers.length; i++) {
            initMDSHandlers[i]();
        }
    };

    var init = function () {
        // Register MDS handler
        if ('undefined' != typeof g_MinimalDownload && g_MinimalDownload && (window.location.pathname.toLowerCase()).endsWith('/_layouts/15/start.aspx') && 'undefined' != typeof asyncDeltaManager) {
            asyncDeltaManager.add_endRequest(initMDS);
        } else {
            for (var i = 0; i < initHandlers.length; i++) {
                initHandlers[i]();
            }
        }
    };

    var registerInit = function (handler) {
        initHandlers.push(handler);
    };

    var registerInitMDS = function (handler) {
        initMDSHandlers.push(handler);
    };

    var domReady = (function (handler) {
        var fns = [];
        var listener;
        var loaded = (document.documentElement.doScroll ? /^loaded|^c/ : /^loaded|^i|^c/).test(document.readyState);

        if (!loaded) {
            document.addEventListener('DOMContentLoaded', listener = function () {
                document.removeEventListener('DOMContentLoaded', listener);
                loaded = 1;
                while (listener = fns.shift()) listener();
            });
        }

        return function (fn) {
            loaded ? setTimeout(fn, 0) : fns.push(fn);
        };
    })();


    var attachToLoad = function (functionToAttach) {
        registerInit(functionToAttach);
        registerInitMDS(functionToAttach);
       domReady(function () {
           init();
        });
    };

    _.AttachToLoad = attachToLoad;

    // THIS WILL PROTECT YOUR GLOBAL VAR FROM THE GARBAGE COLLECTOR
    window.LifeCycleHelper = _;
    if (window.Function != 'undefined' && typeof (Function.registerNamespace) == 'function') {
        Function.registerNamespace('LifeCycleHelper');
    }
})({});

var theCodeYouWantToRun = function () {
    alert('theCodeYouWantToRun');
};

window.LifeCycleHelper.AttachToLoad(theCodeYouWantToRun); 

More Information on how to work with lifecycle and MDS

0

I've found the issue. All or the functions has to be inside window.onload = function (). Then it works.

<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>
1
  • The way you attach is not best practise and will not work in certain scenarios (MDS for example).
    – Mx.
    Commented Jul 27, 2016 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.