HTML5 Onload and Preload Attributes
Web pages can contain a variety of scripts to accomplish tasks such as displaying rotating images, tracking a visitor’s history on your site or even letting users fill out forms. However, long-loading scripts delay DOM construction and page rendering.
Fortunately, html5 onload allows developers to load external scripts asynchronously, which improves web page loading times and user experience.
The onload attribute is used to associate a function or script with an HTML element. The event handler function is executed when the web page finishes loading, and a message is displayed in the browser to notify the user that the page has finished loading.
The onload function is a powerful tool for web developers, as it can be used to trigger a variety of functions when the page has loaded, including displaying a pop-up window or an alert message. The onload function can also be used to set up page elements that require user input, such as forms or search boxes, so they are ready for use when the page loads.
The onload attribute fires a script when an object has loaded. It’s most often used within the
This event also fires if the browser autofills a form field with login or password data, or the user clicks on a button. This is why many sites with a login or registration form use onload to wait for the DOMContentLoaded event before autofilling any information.
You can also use the loading attribute on
The preload attribute is suited for resources that are typically discovered late by the browser, and can be used with a number of different file types including CSS, JS, fonts, and images. Supplying an as attribute will help the browser identify the resource, set appropriate headers, and determine whether it already exists in the cache.
For example, hero images and large runs of text rendered with Web fonts can be LCP candidates, and will benefit from a well-placed preload hint to load and render these critical bits of content faster. Use the
Preloading is a powerful way to improve page performance by prioritizing the loading of important resources ahead of time. However, it can also interfere with rendering if overused, especially if non-essential files are being prefetched by the browser in large quantities. This can cause a busy browser to delay the download of important render-blocking resources.
Browsers can execute a variety of programs to modify pages dynamically, such as rotating pictures or processing form data. Scripts can also be used to validate forms and ensure that input conforms to predetermined ranges of values.
Onload is an event triggered when an HTML object loads successfully. It is most commonly used with the