Detect a img src change

2019-01-25 13:50发布

问题:

I'am trying to detect if the source of a image is changed.

In my case the src is changed from jquery, and i have no right's to change the jquery file. So im trying to detect the src change from a img element.

I would like to see the source if the src is changed, just for testing

This is my current code:

var divimg = document.getElementById("img_div");
divimg.onchange = alert(divimg.getElementsByTagName('img')[0].src);

On the page load the alert react's and shows me the src, but not on a src change from jquery

回答1:

DOMAttrModified might work, no idea about that...but onload works definitely fine for me. Here's the fiddle with the demo. http://jsfiddle.net/QVqhz/



回答2:

You could do it, however it would only be supported by new browsers that implement the DOM mutation events...

divimg.addEventListener("DOMAttrModified", function(event) {
    if (event.attrName == "src") {
       // The `src` attribute changed!
    }
});


回答3:

Every time the src attribute is changed the browser will immediately go off and fetch the image. Once the image is returned to the browser the browser will trigger the loaded event on the image element. So you can effectively monitor src changing by setting a callback on this event. You could do something similar to the following code example.

var img = $("<img />");
img.load(function() { console.log("loaded"); });
img.attr("src", "http://static.adzerk.net/Advertisers/ecc536e9e1204b7faccb15621f27d7bc.jpg");


回答4:

Analysis

  1. load event is triggered when src attribute of <img /> is changed or set

  2. If user didn't write src attribute in <img />, browser will fill out src attribute automatically (such as data:image/png;base64,...) to prevent 204 Error. This will also trigger load event.

Conclusion

  1. Basically use load event, but check whether it is default image or not. (Probably, default image would be 1 x 1 pixel)

    • Assumption - your image is bigger than 1 x 1 pixel

Solution

$('img').load(function() {
    var imageObj = $(this);
    if (!(imageObj.width() == 1 && imageObj.height() == 1)) {
        console.log('Image source changed');
    }
});


回答5:

var img = document.querySelector("#img_div img"),
observer = new MutationObserver((changes) => {
  changes.forEach(change => {
      if(change.attributeName.includes('src')){
        console.dir(img.src);
      }
  });
});
observer.observe(img, {attributes : true});


回答6:

I think there is no event for that, you can create your own 'event':

var divimg = document.getElementById("img_div"),
    prevSrc;
setInterval(function() {
    if (divimg.src != prevSrc) {
        prevSrc = divimg.src;
        onSrcChange();
    }
}, 1000); // 1000ms = 1s

function onSrcChange() {
    // do something
}