JavaScript onloadstart
Event: Resource Loading Started
The onloadstart
event in JavaScript is triggered when the browser begins to load a resource, such as an image, video, or audio file. This event provides a crucial point for web developers to perform actions at the very start of the resource loading process. This article will guide you through the usage of the onloadstart
event, including its syntax, attributes, and practical examples.
What is the onloadstart
Event?
The onloadstart
event is an event handler that fires when the loading process of a resource begins. It is part of the HTML media element event model, which means it applies primarily to elements like <audio>
, <video>
, and <img>
when they begin fetching their respective media resources. The event is useful for implementing loading indicators, monitoring resource loading performance, or any action that should occur when a resource starts to load.
Purpose of the onloadstart
Event
The primary purposes of the onloadstart
event are to:
- Indicate resource loading: Display a loading message or animation as soon as resource fetching starts.
- Monitor loading initiation: Track when a resource starts to load for performance analysis and debugging.
- Initialize pre-loading tasks: Perform pre-loading tasks like setting up variables or initializing UI elements before resource availability.
Syntax of the onloadstart
Event
The onloadstart
event handler can be added directly to the HTML element or through JavaScript.
HTML Syntax:
<element onloadstart="yourFunction()">
Where element
is an HTML element that supports the onloadstart
event (e.g., <img>
, <video>
, <audio>
), and yourFunction()
is the JavaScript function to be executed when the event is triggered.
JavaScript Syntax:
element.onloadstart = function() {
// Your code here
};
Or using addEventListener
:
element.addEventListener('loadstart', function() {
// Your code here
});
Here, element
is the reference to your HTML element obtained using document.getElementById()
or other similar DOM methods.
Important Attributes
The onloadstart
event itself does not have any specific attributes, but the event object passed to the event handler function does contain useful properties and methods that can be used for event management.
Property | Type | Description |
---|---|---|
`type` | String | The type of the event (in this case, `loadstart`). |
`target` | Element | The HTML element that triggered the event. |
`timeStamp` | Number | The timestamp of when the event occurred (in milliseconds). |
Examples of onloadstart
Event Usage
Let’s explore several examples illustrating how to use the onloadstart
event effectively in various scenarios.
Example 1: Basic Loading Message for an Image
This example shows how to display a message when an image starts to load.
<!DOCTYPE html>
<html>
<head>
<title>onloadstart Example 1</title>
</head>
<body>
<p id="loading-status-1">Image status: Not loading</p>
<img id="myImage-1" src="https://dummyimage.com/300x200/000/fff" alt="Test Image">
<script>
const imgElement1 = document.getElementById('myImage-1');
const statusElement1 = document.getElementById('loading-status-1');
imgElement1.onloadstart = function() {
statusElement1.textContent = 'Image status: Loading started...';
};
imgElement1.onload = function() {
statusElement1.textContent = 'Image status: Loaded';
}
</script>
</body>
</html>
Output:
Initially: “Image status: Not loading”. Then when the image starts to load it shows “Image status: Loading started…” and when the image load finishes it changes to “Image status: Loaded”.
Example 2: Loading Indicator for a Video
This example shows how to display a simple loading indicator when a video starts to load.
<!DOCTYPE html>
<html>
<head>
<title>onloadstart Example 2</title>
</head>
<body>
<div id="loading-indicator-2" style="display: none;">Loading Video...</div>
<video id="myVideo-2" width="320" height="240" controls>
<source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script>
const videoElement2 = document.getElementById('myVideo-2');
const indicatorElement2 = document.getElementById('loading-indicator-2');
videoElement2.onloadstart = function() {
indicatorElement2.style.display = 'block';
};
videoElement2.onloadeddata = function() {
indicatorElement2.style.display = 'none';
}
</script>
</body>
</html>
Output:
Initially, the video loads with no indicator shown. As the video starts to load the text “Loading Video…” appears and disappears when the loading finishes.
Example 3: Logging Loading Times
This example demonstrates how to use onloadstart
event to record the timestamp of when the loading process begins.
<!DOCTYPE html>
<html>
<head>
<title>onloadstart Example 3</title>
</head>
<body>
<p id="loading-log-3">Loading log:</p>
<img id="myImage-3" src="https://dummyimage.com/150x100/000/fff" alt="Small Test Image">
<script>
const imgElement3 = document.getElementById('myImage-3');
const logElement3 = document.getElementById('loading-log-3');
imgElement3.onloadstart = function(event) {
const startTime3 = event.timeStamp;
logElement3.textContent += `\nLoad started at ${startTime3}ms`;
};
imgElement3.onload = function() {
const endTime3 = performance.now();
logElement3.textContent += `\nLoad finished at ${endTime3}ms`;
}
</script>
</body>
</html>
Output:
The timestamp of when the image starts to load will be displayed when the loading starts and when it finishes.
Example 4: Using addEventListener
This example demonstrates using addEventListener
to attach multiple event listeners for different functionalities.
<!DOCTYPE html>
<html>
<head>
<title>onloadstart Example 4</title>
</head>
<body>
<p id="status-msg-4">Status: Not Started</p>
<img id="myImage-4" src="https://dummyimage.com/200x150/000/fff" alt="Test Image">
<script>
const image4 = document.getElementById('myImage-4');
const status4 = document.getElementById('status-msg-4');
image4.addEventListener('loadstart', function() {
status4.textContent = 'Status: Loading...';
});
image4.addEventListener('load', function() {
status4.textContent = 'Status: Loaded';
});
</script>
</body>
</html>
Output:
Initially, “Status: Not Started”, then after starting “Status: Loading…” then after the image finishes loading it becomes “Status: Loaded”.
Real-World Applications of onloadstart
Event
The onloadstart
event is a valuable tool for various applications:
- Preloading Resources: Implement a preload strategy that shows a loading indicator to users while resources are fetched.
- Performance Monitoring: Gather data on the time it takes for assets to start downloading.
- User Experience: Show visual feedback to users, indicating that content is being loaded to keep them engaged.
Browser Support
The onloadstart
event is widely supported across modern browsers, ensuring your implementation will work consistently for the majority of users. 🚀
| Browser | Support |
| ————– | ——- |
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Edge | Yes |
| Opera | Yes |
| Internet Explorer | No |
Note: While onloadstart
has good support, older browsers like Internet Explorer do not support it. Always test on multiple browsers. 🧐
Conclusion
The onloadstart
event offers an essential tool for web developers to enhance the user experience by managing and monitoring the loading process of resources. Whether you are creating simple loading indicators or complex resource-tracking systems, understanding and using the onloadstart
event will make your web applications more robust and user-friendly. Start implementing the examples from this guide and discover the power of this event in your web projects.