0

I luckily found this code on the net for continuos add on onload from a different subject completely

function myPluginLoadEvent(func) {
        // assign any pre-defined functions on 'window.onload' to a variable
        var oldOnLoad = window.onload;
        // if there is not any function hooked to it
        if (typeof window.onload != 'function') {
            // you can hook your function with it
            window.onload = func
        } else { // someone already hooked a function
            window.onload = function () {
                // call the function hooked already
                oldOnLoad();
                // call your awesome function
                func();
            }
        }
    }

    // pass the function you want to call at 'window.onload', in the function defined above
    myPluginLoadEvent(func);

However, this only allow for one add on onload call. How do I loop this for multiple on load call such as for i, 1++ ? Many thanks in advance.

jason
  • 15
  • 3

1 Answers1

1

The code you posted will work repeatedly. Each time it's called, oldOnLoad contains whatever was previously assigned to window.onload, which could be the result of a previous use. So it just keeps chaining all the functions.

However, the modern approach is to use addEventListener rather than assigning to window.onload.

window.addEventListener("load", func);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Really? . I am using this function to reload window onload after scrolling a YoutubeAPIIframe iframe div. The APIIframeElement only seems to load once and not any more after that. What have I done wrong then, please? – jason Nov 23 '17 at 12:20
  • When you reload the window, everything starts fresh. I was talking about using the function multiple times in the same script execution. – Barmar Nov 23 '17 at 17:38
  • Thanks Barmar for looking at my post. So is there a possible way to update the onload function after each time new data loaded. Using the above code, I some how had it updated but only once!! Please have alook at my other post to see what I mean. https://stackoverflow.com/questions/47425997/youtube-on-scroll – jason Nov 23 '17 at 22:38
  • I'm not sure I understand your issue. When you reload the page, all the Javascript will be run again. So just put what you want in the regular Javascript. If you need to remember data between reloads, you can use `localStorage` or `sessionStorage`. – Barmar Nov 24 '17 at 06:33
  • yeah, half of the time I am not sure what I am doing either :-(. However, this is part of another problem with my coding. Now I didn't even have to use it at all. I will read the code again and try to absorb it. Thanks for your comment and reply in the last couple days. There are such a great and support community here. Again, thank you all. – jason Nov 24 '17 at 07:46