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
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>
.