JavaScript - overwriting .onload prototype of HTMLImageElement(s)

前端 未结 4 2364
花落未央
花落未央 2020-12-21 17:50

Is it possible to bind an onload event to each image, declaring it once? I tried, but can\'t manage to get it working... (this error is thrown: Uncaught

4条回答
  •  盖世英雄少女心
    2020-12-21 18:23

    I've written something similar some time ago to check if an image is loaded or not, and if not, show a default image. You can use the same approach.

    $(document).ready(function() {
        // loop every image in the page
        $("img").each(function() {
            // naturalWidth is the actual width of the image
            // if 0, img is not loaded
            // or the loaded img's width is 0. if so, do further check
            if (this.naturalWidth === 0) { // not loaded
                this.dataset.src = this.src; // keep the original src
                this.src = "image404.jpg";
            } else {
                // loaded
            }
        });
    });
    

提交回复
热议问题