Search code examples
imagepolymerdom-repeat

Check if Resource Exists in Polymer Framework


I am trying to pull in product images in a dom-repeat template, but am getting 404 errors for missing resources showing up in the console.log. I would like to clean up the log with more legitimate errors.

<template is="dom-repeat" items="" index-as="index">
  <lazy-image class="center"
    placeholder="/images/placeholder.png"
    src="https://www.images.com/[[formatImg(item.id)]].png"
    style="width: 24pt; height: 24pt;">
  </lazy-image>       
</template>

...

formatImg(id) {
  if(typeof id != 'null') return id.replace(' ', '%20');
}

I've seen some documentation on on-error events, but am not seeing a straight forward path to implement them into the Polymer framework.

Is there a way to handle these GET requests so they don't get logged?


Solution

  • Short answer:

    Sadly, no.

    It's not a "can't do it in Polymer" thing. At the time of writing, handling 404s to prevent a console error is not possible at all from the developer's point of view.

    Longer answer:

    AFAICT there is no way for a web developer to prevent a 404 from being logged by a browser as an error. If a browser is asked "get this thing please" or even "hey can you check if this is a thing?" and the answer is "that's not a thing", it is up to the browser what it does with that information. Right now, what it does (welp, Chrome anyway - I haven't researched what the others do) is "log an error to the console". Always. No matter what.

    You can (as the end user) turn that behavior off in your browser. But you can NOT (as a developer) "catch" the error and handle it to keep the browser happy. Even if you DO handle the error and give the browser something that exists instead of the 404-causing resource, it will STILL be logged in the console as an error:

    <!-- STILL CAUSES A 404 ERROR TO BE LOGGED TO THE CONSOLE -->
    <img id="myimg" src="imagethatdoesntexist.gif" onerror="this.onerror=null;this.src='imagethatexists.gif';">
    

    Source: Trial and error && this thread https://bugs.chromium.org/p/chromium/issues/detail?id=124534#c17