Oleksandr Telesh Oleksandr Telesh - 2 months ago 5
jQuery Question

Error handling with jquery v3 and load event

The jquery v2~ supports load function:

$(selector).load(function () {}).error(function(){});


The jquery v3~ doesn't support load function and we need to use the on function:

$(selector).on('load', function () {});


How can I handle errors with the on function?

Answer

Just to be sure, jQuery 3 still supports .load() to load content. Only the event listener creation and trigger needs to use .on() and .trigger().

// jQuery 2
$("selector").load(function() {
    console.log("I'm loaded!");
});
$("selector").load();

// jQuery 2 + jQuery 3
$("selector").on("load", function() {
    console.log("I'm loaded!");
});
$("selector").trigger("load");

The error handling is the same. .error() is deprected, use on again:

// jQuery 2 + jQuery 3
$("selector").on("load", function() {
    console.log("I'm loaded!");
}).on("error", function() {
    console.log("I'm having errors!");
});
$("selector").trigger("error");

Or combine both event listeners in a single .on():

// jQuery 2 + jQuery 3
$("selector").on({
    load: function() {
        console.log("I'm loaded!");
    },
    error: function() {
        console.log("I'm having errors!");
    }
});
$("selector").trigger("load");
$("selector").trigger("error");
Comments