I want to ask a question about the Javascript’s onload
.
I’m writing a JSP page with the code <%@ include file ="body.jsp"
. The included body.jsp
contains:
<table onload="function()">
This should load the javascript function, but it doesn't appear to have any effect on the page. Is onload
only usable on the body
tag?
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.
onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see "Supported HTML tags" below).
The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded. The function that is required to be executed is assigned as the handler function to this property.
JavaScript has a window onload event to launch certain functions whenever a web page is loaded. The onload event is also used for verification of type and version of visitor's browser. Further cookies can also be checked through the onload attribute. The attribute of onload triggers when the object is loaded in HTML.
Onload can only be used for <body>
, <img>
, <script>
, <iframe>
tags, because it tells you when an external resource (image, script, frame) or the whole page (body) has been loaded
Since HTML5 these can also fire a load event: <link>
, <style>
, <input type=image>
, <object>
Support for these can still be a hit or miss though (e.g. older Android browsers)
Why not just include it via a <script tag>
?
Inside your .jsp file
<script> window.onload = function() { alert("Hello!"); } // or to execute some function window.onload = myFunction; //notice no parenthesis </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With