Correct Usage of jQuery .on() Method with Load Event

Dec 02, 2025 · Programming · 24 views · 7.8

Keywords: jQuery | event handling | load event | event delegation

Abstract: This article explains the limitations of the load event in jQuery, particularly its non-bubbling nature that prevents event delegation using the .on() method. It provides best practices for handling load events, including direct attachment and alternative approaches.

Introduction to jQuery .on() Method

The jQuery .on() method is a versatile function for attaching event handlers to elements. It supports both direct event binding and event delegation, which allows handling events for dynamically added elements by binding the event to a parent element and triggering based on child selectors.

Non-Bubbling Nature of the Load Event

According to the jQuery documentation, the load event does not bubble in all browsers. This means that for elements like <img>, the event is not propagated up the DOM tree, making it unsuitable for event delegation with .on().

In all browsers, the load, scroll, and error events do not bubble. Such events are not supported for use with delegation.

Correct Usage of .on() with Load Event

To handle load events, you should directly attach the event handler to the element generating the event, rather than using delegation. Alternatively, execute the code after the element is added to the DOM.

For example, in the provided code snippet:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
        // Code to execute after appending
        alert('started');
    });
});

Instead of using $(document).on('load', '.abc', function() {...}), which is ineffective due to non-bubbling, the alert is placed inside the click handler after appending.

Alternative Approaches and Best Practices

Other answers highlight the difference between window.onload and document.ready. window.onload fires after all content is loaded, while document.ready triggers when the DOM is ready. For handling initial load, use jQuery(window).on("load", function(){...}) or jQuery(document).ready(function(){...}) as appropriate.

Ensure consistency in using jQuery or $ throughout your code to avoid confusion.

Conclusion

Understanding the limitations of the load event is crucial for effective event handling in jQuery. By directly attaching handlers or executing code post-addition, you can achieve the desired functionality without relying on unsupported event delegation.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.