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);