Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Arno Welzel Newsgroups: comp.lang.javascript Subject: Re: missing image error Date: Tue, 4 Aug 2020 10:29:34 +0200 Lines: 41 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit X-Trace: individual.net LIcSxHfw1vjykNaitYIb6QoH3MMtrU65SxmINwZmS6FAJoo5tJ Cancel-Lock: sha1:3Lj/fRSOH3TjC7rMKTcOMvmjJGA= In-Reply-To: Xref: csiph.com comp.lang.javascript:38641 Andrew Poulos: > I'm dynamically adding images to a page using > > let img = new Image(); > > img.src = 'images/' + name + '.jpg'; > img.setAttribute("onerror", "this.onerror=null; > this.src='images/imagenotfound.png'"); > ... > > and the page works as expected. That is, when the image is not available > 'imagenotfound' is shown in its place. > > The client tests the page with the console open and each time an image > is unavailable they see a 404 error. I've tried explaining that it needs > to error before it can know to replace it with 'imagenotfound' but they > would prefer that image's 404 error not show. > > Is there a way to trap the 404 so it doesn't show in the console? > Or is there some other way I can try to get the image and thereby be > able to trap the 404? No. That's the reason why there is a console - to see what is going on. Without trying to load an image and getting the 404 error the "onerror" attribute would not work at all. The only way to avoid 404 errors would be a wrapper script on the *server* which will either return the actual image or a placeholder if the image can not be loaded: Where "server-side-loader" is a PHP script etc. which will try to load the specificed image file and if this is not possible return the placeholder. -- Arno Welzel https://arnowelzel.de