Warrior Warrior - 2 months ago 15
Javascript Question

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

How can a JavaScript function in JSP be called during page load without using

<body onload="disableView()">


I have to call this function in a few JSP's on page load but JSP's are divided into header, footer and pageContent sections and the body tag droped into header section and it has to be in header section only. So in some of the pages I have to call JavaScript function on page reload/load in pageContent section where I won't get
<body>
tag to put the
onload
in. How can I solve this?

Answer

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>