sanjar-notes / web_dev_fundamentals

The basics - HTML, CSS, Javascript and more
https://sanjar-notes.github.io/web_dev_fundamentals/
3 stars 0 forks source link

Detect failed img nodes, server controlled img.alt #93

Open sanjarcode opened 1 year ago

sanjarcode commented 1 year ago
function actionWhenImageDidntLoad() {
  console.log("Image couldnt load");
}

document.querySelectorAll("img").forEach((imgNode) => {
  const isFetching = !imgNode.complete;
  if (isFetching) {
    imgNode.addEventListener("error", actionWhenImageDidntLoad);
    return;
  }

  const couldntLoadImage = !imgNode.naturalWidth;
  if (couldntLoadImage) {
    actionWhenImageDidntLoad();
    return;
  }
});

context: i was working on a traditional web app, where JS runs after page DOM has settled. the goal was to makeimg.alt server controlled (assume I own the image server, which would sent the alt with an error message).

sanjarcode commented 1 year ago

problem: can't access asset call error. where is it stored btw. Maybe it is accessible in the error event case. what about the already loaded ones.

if devTools have it, it may be stored by the page too.