Add my own window.onload safely without overwriting old ones

Posted on In QA

My webpage has one existing window.onload javascript function defined by a javascript plugin in the <head> section. Now, I defined a new one and add it to the end of the HTML page:

<script type="text/javascript">
    window.onload = function () {
         // great work here
    }
</script>

I find the new one overwrites the old one in the plugin and the old one is not executed at all.

How to add my onw window.onload functions without overwriting old ones?

I find this little trick by rewriting the javascript as follows:

<script type="text/javascript">
    var oldOnload = window.onload;

    window.onload = function () {

        if (typeof oldOnload == 'function') {
          oldOnload();
        }

        // great work here
    }
</script>

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *