Search code examples
javascriptdom-events

Run Two Functions (One In External File, One In Inline Javascript) On window.onload


I'm developing a website and I have an external JavaScript file that is linked to every page of the site which executes when the window.onload event is fired. The JavaScript executes fine on all pages which do not contain any inline JavaScript.

Any page that contains inline JavaScript also contains a JavaScript function which executes when the window.onload event is fired.

The problem I'm having is that the external JavaScript does not execute when window.onload is fired, only the internal JavaScript does. It appears as if the inline JavaScript function overwrites the function from the external JavaScript file.

I know that my external JavaScript file is first executed and then the inline JavaScript is executed. Is there anyway that I can execute both functions on window.onload?


Solution

  • How about changing the script that executes second to something like this:

    var onload = function () {
        // Do something
        alert('Hello');
    };
    
    if(window.onload) {
        // If a function is already bound to the onload event, execute that too.
        var fn = window.onload;
        window.onload = function () {
            fn();
            onload();
        };
    } else {
        window.onload = onload;
    }
    

    Or use a library like jQuery which lets you do:

    $(document).ready(function() {
        alert('Hello');
    }