How to run JavaScript on page load without `<body onload>`, especially in JSP fragments without a `<body>` tag?

I want to dynamically populate parts of my page with server data once the page loads, but I can’t use the onload attribute in JSP fragments. Also, I prefer not to use jQuery. What’s the best way to run javascript on page load in this scenario?

I’ve worked a lot with JSP fragments in legacy enterprise apps, and I’ve often needed to run JavaScript on page load without relying on <body onload>. In those cases—especially when there’s no <body> tag to hook into—I usually look for cleaner, script-based approaches instead of relying on HTML attributes

You can assign your function to window.onload, which runs after the entire page loads:

window.onload = function() {
  foo();
};

This works regardless of whether you have access to the tag and doesn’t require jQuery.

Yeah, I’ve run into that in modular JSP setups too. One reliable way to run JavaScript on page load, without waiting for images and styles, is to use DOMContentLoaded. It’s super effective in fragments:

document.addEventListener("DOMContentLoaded", function() {
  foo();
});

This approach lets you run JavaScript on page load when just the DOM is ready, which is often what you want for UI logic and works seamlessly in JSP structures without a <body>.

If you can control where the script tag is placed, put your JavaScript just before the closing </body> tag:

<script>
  foo();
</script>

Since the DOM will already be loaded by then, your function runs immediately without extra event listeners.

Hope this was helpful :slight_smile: