I have an image that is loaded using base64 however for some reason the image isn't loading so I can show a temp image, but need to know exactly why the image isn't loading. How can capture the actual error?
<img [src]="sanitizer.bypassSecurityTrustUrl('data:'+image.mimeType+';base64, '+ image.frontImage)"
onerror="getError($event)" />
in my getError nothing happens. I get a Uncaught ReferenceError: getError is not defined
getError(event){
console.log(event);
}
Related
When you load a grid of images there is a chance that one or more images are not found. In those cases, I do not want to show a blank space or an ugly browser-default "Image Not Found"-icon. Instead, I want to show a default image or some kind of thumbnail.
One way to achieve this is to use the onerror-tag like this:
<img src="example.png" onerror="this.onerror=null;this.src='not-
found.jpg';" alt="Some example image I expect to load!" />
When an error occurs, e.g the image resource is not found, the onerror-tag is executed and the src of the image is set to a default not-found image. this.onerror=null is to avoid an infinite loop in case the not-found image is also not found.
But this method seems to be deprecated.
Every Google result shows the onerror-method when I search on how to handle not-found images like this.
So, what would be the best way to show a default image when an image is not found?
I thought that <picture> worked like this, but it doesn't.
<picture>
<source srcset="example.webp" type="image/webp">
<source srcset="example.jpg" type="image/jpeg">
<img alt="" src="not-found.jpg">
</picture>
Use the GlobalEventHandler onerror instead: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
When a resource (such as an <img> or <script>) fails to load, an error
event using interface Event is fired at the element that initiated the
load, and the onerror() handler on the element is invoked. These error
events do not bubble up to window, but can be handled with a
EventTarget.addEventListener configured with useCapture set to true.
<div className="image" style={{ backgroundImage: `url(${entity.image_url})`}} />}
I am setting a background-image by passing the url as an inline style attribute. However, there will be times when the image link is broken. I am familiar with the onerror event of the tag. However I am not familiar with how I can detect a broken link when setting a background image. I was thinking of attempting to load the image in a hidden and use the onerror attribute, but this requires me to load the image twice, which is wasteful. What is a better way to do this?
The old school style is to pre load all images.
Preload Images
Now you has the Image in a js object and does not to load the image again or twice. By this you can also check if its broken Detect broken images. And for sure if you use the clever AJAX way of life you can also detect and replace broken images.
why not write some JS and test the entity.image_url. if you don't get an object back it will come up as undefined or null. wrtie an if statement for both to cover the possibilities.
if (entity === undefined || entity === null) {
//write an error message
} else {
//drop a dynamic template literal into your html
//you can either appendChild() or build a string and user innerHTML
}
This is how I was able to do it in React:
import noImage from <local_image_path>;
{(entity && entity.image) ?
<div style={{backgroundImage: `url(${entity.image}), url(${noImage})`}}/> :
<div style={{backgroundImage: `url(${noImage})`}}/>
}
This takes care of two cases. Case 1: broken image link. If there is a 404 on the entity.image url, noImage is loaded. Case 2: entity.image is undefined, noImage is loaded.
Hi I have the following html inside one of my javascript files.
function addToInfoWindow(infoWindowContent)
{
infoWindowString = '<div id="infoWindowString">'+
'<img src="assets/images/rails.png">'+
'<h2>You Clicked:</h2>'+
'<p>'+infoWindowContent+'</p>'+
'<p>See more info</p>'+
'<p>see news</p>'+
'</div>';
infoWindow.setContent(infoWindowString);
}
The problem is I cannot get the image to show up in the info window.
I realize this \could be because rails has some sort of helper function to show images in its webpages. But I haven't been able to find how to call it or what it is. Can someone help please.
EDIT- Changed to following after the response below:
function addToInfoWindow(infoWindowContent)
{
infoWindowString = '<div class="infoWindowString">'+
'<img src="/Users/AM/Documents/RailsWS/cmdLineWS/Businesses/app/assets/images/rails.png">'+
'<h2>You Clicked:</h2>'+
'<p>'+infoWindowContent+'</p>'+
'<p>See Menus</p>'+
'<p>Upload a Menu</p>'+
'</div>';
infoWindow.setContent(infoWindowString);
}
But image still not showing up :(
If you're using the default setup with rails asset packaging it will append a timestamp onto asset filenames meaning just browsing to /assets/images/foo.jpg won't necessarily give you what you want.
The rails helper to get an image tag is just image_tag 'example.jpg'. OR if you just want the url, image_url 'foo.jpg'.
For any given image you want stored you could attach it to a data attribute, for instance in a view you could do:
<a id="image_link" href="#" data-image-url="<%= image_url 'foo.jpg' %>">Click to see image</a>
You can get that path anywhere in jQuery using
var imageUrl = $('a#image_link').data('image-url')
You are using a relative URL for your image (assets/images/rails.png), so the browser will try to load it from an address relative to the current page. For example, if the image is at
http://example.com/assets/images/rails.png
but you are currently at
http://example.com/something/somepage.html
the browser will try to load it from
http://example.com/something/assets/images/rails.png
and it will fail.
You should be using an absolute URL.
Is there a way to control the load order of images on a web page? I was thinking of trying to simulate a preloader by first loading a light-weight 'LOADING' graphic. Any ideas?
Thanks
Use Javascript, and populate the image src properties later. The # tells the browser to link to a URL on the page, so no request will be sent to the server. (If the src property was empty, a request is still made to the server - not great.)
Assemble an array of image addresses, and recurse through it, loading your images and calling a recursive function when the onload or onerror method for each image returns a value.
HTML:
<img src='#' id='img0' alt='[]' />
<img src='#' id='img1' alt='[]' />
<img src='#' id='img2' alt='[]' />
JS:
var imgAddresses = ['img1.png','img2.jpg','img3.gif'];
function loadImage(counter) {
// Break out if no more images
if (counter==imgAddresses.length) { return; }
// Grab an image obj
var I = document.getElementById("img"+counter);
// Monitor load or error events, moving on to next image in either case
I.onload = I.onerror = function() { loadImage(counter+1); }
//Change source (then wait for event)
I.src = imgAddresses[counter];
}
loadImage(0);
You could even play around with a document.getElementsByTagName("IMG").
By the way, if you need a loading image, this is a good place to start.
EDIT
To avoid multiple requests to the server, you could use almost the same method, only don't insert image elements until you're ready to load them. Have a <span> container waiting for each image. Then, loop through, get the span object, and dynamically insert the image tag:
var img = document.createElement("IMG");
document.getElementById('mySpan').appendChild(img);
img.src = ...
Then the image request is made only once, when the element is created.
I think this article https://varvy.com/pagespeed/defer-images.html gives a very good and simple solution. Notice the part which explains how to create "empty" <img> tags with:
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="your-image-here">
to avoid <img src="">
To display a loading image, just put it in the HTML and change it later at the appropriate moment/event.
Just include the 'loading' image before any other images. usually they are included at the very top of the page and then when the page loading completes, they are hidden by a JS.
Here's a small jQuery plugin that does this for you: https://github.com/AlexandreKilian/imageorder
I've got a web page that automatically reloads every few seconds and displays a different random image. When it reloads, however, there is a blank page for a second, then the image slowly loads. I'd like to continue to show the original page until the next page is loaded into the browser's memory and then display it all at once so that it looks like a seamless slideshow. Is there a way to do this?
is the only thing changing the image? if so it might be more efficient to use something like the cycle plugin for jQuery instead of reloading your whole page.
http://malsup.com/jquery/cycle/
Here is the JS needed if you used jQuery -
Say this was your HTML:
<div class="pics">
<img src="images/beach1.jpg" width="200" height="200" />
<img src="images/beach2.jpg" width="200" height="200" />
<img src="images/beach3.jpg" width="200" height="200" />
</div>
Here would be the needed jQuery:
$(function(){
$('div.pics').cycle();
});
no need to worry about different browsers- complete cross browser compatibility.
If you're just changing the image, then I'd suggest not reloading the page at all, and using some javascript to just change the image. This may be what the jquery cycle plugin does for you.
At any rate, here's a simple example
<img id="myImage" src="http://someserver/1.jpg" />
<script language="javascript">
var imageList = ["2.jpg", "3.jpg", "4.jpg"];
var listIndex = 0;
function changeImage(){
document.getElementById('myImage').src = imageList[listIndex++];
if(listIndex > imageList.length)
listIndex = 0; // cycle around again.
setTimeout(changeImage, 5000);
};
setTimeout(changeImage, 5000);
</script>
This changes the image source every 5 seconds. Unfortunately, the browser will download the image progressively, so you'll get a "flicker" (or maybe a white space) for a few seconds while the new image downloads.
To get around this, you can "preload" the image. This is done by creating a new temporary image which isn't displayed on the screen. Once that image loads, you set the real image to the same source as the "preload", so the browser will pull the image out of it's cache, and it will appear instantly. You'd do it like this:
<img id="myImage" src="http://someserver/1.jpg" />
<script language="javascript">
var imageList = ["2.jpg", "3.jpg", "4.jpg"];
var listIndex = 0;
var preloadImage = new Image();
// when the fake image finishes loading, change the real image
function changeImage(){
document.getElementById('myImage').src = preloadImage.src;
setTimeout(preChangeImage, 5000);
};
preloadImage.onload = changeImage;
function preChangeImage(){
// tell our fake image to change it's source
preloadImage.src = imageList[listIndex++];
if(listIndex > imageList.length)
listIndex = 0; // cycle around again.
};
setTimeout(preChangeImage, 5000);
</script>
That's quite complicated, but I'll leave it as an exercise to the reader to put all the pieces together (and hopefully say "AHA!") :-)
If you create two divs that overlap in the image area, you can load one with a new image via AJAX, hide the current div and display the one with the new image and you won't have a web page refresh to cause a the "bad transition". Then repeat the process.
If there's only a small number of images and they're always displayed in the same order, you can simply create an animated GIF.
Back in the dark old days (2002) I handled this kind of situation by having an invisible iframe. I'd load content into it and in the body.onload() method I would then put the content where it needed to go.
Pre-AJAX that was a pretty good solution.
I'm just mentioning this for completeness. I'm not recommending it but it's worth noting that Ajax is not a prerequisite.
That being said, in your case where you're simply cycling an image, use Ajax or something like the jQuery cycle plug-in to cycle through images dynamically without reloading the entire page.