Is there a way to tell the browser to look down a list of image URLs until it finds one that works? Pure HTML would be preferred, but I'm guessing JavaScript is probably necessary here (I'm already using JQuery, so it's not an issue).
EDIT: Thanks for your answers! I'll add a few clarifications:
By "works" I mean the image can be displayed.
I specifically want to do this on the client side.
This seems like a bad idea to me. What is the purpose of this feature? It sounds like you want something equivalent to this:
<img src="/images/file1.jpg" src2="/images/file2.jpg" src3="/images/file3.jpg">
Where the browser would try each file in succession. The problem with this approach is that it significantly increases the http traffic required and the latency. The best approach is to dynamically construct the page using the correct image tags ahead of time. Using a server-side approach you can try to load the image from the disk (or database or wherever the images are) and dynamically include the best url in the page's image tag.
If you insist on doing it client-side, you can try loading multiple image tags:
<img src="file1.jpg" alt="" onerror="this.style.display='none'">
<img src="file2.jpg" alt="" onerror="this.style.display='none'">
<img src="file3.jpg" alt="" onerror="this.style.display='none'">
<img src="file4.jpg" alt="" onerror="this.style.display='none'">
<img src="file5.jpg" alt="" onerror="this.style.display='none'">
<img src="file6.jpg" alt="" onerror="this.style.display='none'">
This will result in a page that appears to have lots of images but they disappear as the page loads. The alt="" is required to make Opera not show the broken image placeholder; the onerror is required for Chrome and IE.
If that's not spiffy enough, and if all your images are the same size, and that size is known, you could stack a bunch of images one on top of the other, so that the first image that loads hides all the others. This worked for me in Opera, FF, and IE8. It loads the last image in the list that exists. Note that this wastes bandwidth and memory because every image is loaded.
<div style="width: 50px; height:38px; background-image: url(file1.jpg);">
<div style="width: 50px; height:38px; background-image: url(file2.jpg);">
<div style="width: 50px; height:38px; background-image: url(file3.jpg);">
<div style="width: 50px; height:38px; background-image: url(file4.jpg);">
<div style="width: 50px; height:38px; background-image: url(file5.jpg);">
<div style="width: 50px; height:38px; background-image: url(file6.jpg);">
<div style="width: 50px; height:38px; background-image: url(file7.jpg);">
</div></div></div></div></div></div>
Finally, there is the JavaScript approach:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
var image_array = ['file1.jpg', 'file2.jpg', 'file3.jpg', 'file4.jpg', 'file5.jpg','file6.jpg' ];
function load_img(imgId, image, images, index) {
image.onerror = function() {
load_img(imgId, this, images, index+1);
};
image.onload = function() {
var element = document.getElementById(imgId);
if (element) {
element.src = this.src;
element.style.display = 'block';
}
};
image.src = images[index];
}
</script>
</head>
<body>
<img id="id_1" alt="" style="display: none;">
</body>
<script>
load_img('id_1', new Image(), image_array, 0);
</script>
</html>
If you're trying setting multiple sources to the image tag depending on the resolution, srcset is the paramenter you're looking for.
<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 1x, images/space-needle-2x.jpg 2x,
images/space-needle-hd.jpg 3x">
If I am reading the specification correctly, you should be able to do this with the HTML object element. <object> tags can be nested and thereby provide a chain of resources that are tried each in turn to be rendered and upon failure the user agent continues with the next one.
Note, though, that this behaviour is/was buggy for several browsers and versions.
Assuming you mean the browser being able to retrieve some content with an HTTP response code 200 for a specific URL, then the answer is : NO from the client side using only HTML.
In other words, you can't have an element (e.g. img) and specify multiple URLs to "try".
Of course you can craft something on the server side: a request comes in for resource X and the server has a list of URLs that "work".
INAJNBAM (I'm not a Javascript Ninja by any means), but in pseudo code, maybe try something like this after the page has loaded: (OR, now that I think about it, this would work well with PHP too)
$images = array('img1.jpg', 'img2.jpg', 'img3.png'....)
foreach $images as $img
{if $img.height > 0px
{print "<img src="$img" />"
end}
};;;;
In fact PHP would be even better because I presume in JS this would result in images flashing up on the screen at the end of the pageload. Try it out in PHP and see if something like this fits your bill.
NOTE: I added 4 semi colons at the end. I know Javascript always wants 'em, I just didn't know where to stick them.
If by saying "works" you mean the image can be loaded, you can use the "load" function on an image( in your case a bunch of images) of jQuery and inside of it declare the functionality that will be fire once the loading of the an image is completed.
If by saying "works" you mean that the HTTP status code is ok then use an ajax call using jquery.
function getUrlStatus(url) {
$.ajax({
url: url,
complete: function(xhr) {
return xhr.status;
}
});
}
You could enter the URL of some server-side application/script that serves up the image from whatever image source it can find.
You could do this in ASP.Net with an HTTPHandler that sends a response of content-type=image/jpg.
Other than ASP.Net there are amny other server-side options such as Perl, PHP...
Related
So this:
<html>
<head>
<style>
img{href:self}
</style>
</head>
<img src="./Sampleimage"/>
</html>
would basically be the code I need, but since I don't know how or even if there is an option to do this, I figured, I have to ask someone more intelligent than me.
I kinda have to do this because I have about 200 images in this html Document, and every single one of them has to link to itself. So a seperate <a> tag for every image wouldn't be very stylish.
Expanding off of WillardSolutions' comment...
document.getElementById("myImg").addEventListener("click", function() {
window.open(this.getAttribute("src"));
});
.clickable {
cursor: pointer;
}
<img id="myImg" class="clickable" src="https://www.w3schools.com/images/compatible_chrome.gif"/>
Open your browser console to see the opening of the URL being blocked...
If you want it to open in a new window/tab use:
window.open(this.getAttribute("src"), '_blank');
Nice idea, but no, as the commenters above have explained.
What you can do is get the source URL of each image using jQuery and append it to the parent <a> element. I would do this on page load rather than on clicking the image, as then the images are ready to click.
I would also suggest using a thumbnail version of the image, otherwise it will take ages for the page to load. (If you do that, you will need to put all the thumbnails in a subdirectory and then remove that subdirectory from the link URL using a replace function).
$( document ).ready(function() {
$("img").each(function(){
var imgUrl = $(this).attr('src');
$(this).parent().attr('href', imgUrl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a><img src="https://cdn.pixabay.com/photo/2018/12/15/02/53/flower-3876195_960_720.jpg" width="200"/></a>
Don't use JS for this simple solution...
<a href="image-src.ext">
<img src="image-src.ext"/>
</a>
if you want the image to be downloadable add the download attribute to <a>. It is really no problem and the faster performance solution. And about 'stylish'... forget about stylish in coding :D
This might be the solution you are looking for.
Here is the fiddle. https://jsfiddle.net/RadekD/bgfpedxv/1/
HTML
<img class="image" src="https://placeimg.com/100/200/nature" />
<img class="image" src="https://placeimg.com/200/200/nature" />
<img class="image" src="https://placeimg.com/300/200/nature" />
JS
var images = document.querySelectorAll('.image');
images.forEach(function(element) {
element.addEventListener("click",function(){
window.location.assign(element.src);
});
});
tl;dr: optimal placeholder image, tiny base64 code in HTML or 1x1 gif image?
I'm in the process of building a portfolio website with many high resolution images. Most are contained in slideshows or hidden divs. So I added a simple lazy loading function to the page.
It all works, but I was wondering what would be the fastest way of loading the placeholder images. Because I was told to never leave the src attribute blank.
I found a very tiny base64 image code on the internets and am using this. But the website contains many images, so the browser is decoding every single base64 image now. Doesn't seem very efficient either.
Would using a single very small 1x1 gif image be more efficient? Or would that add more network requests?
What is the most optimal solution?
Here's the code, almost irrelevant to my question:
<div class="slide">
<button> Click to load images </button>
<img class="lazy" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="http://lorempicsum.com/up/627/200/3" alt="" />
<img class="lazy" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="http://lorempicsum.com/nemo/627/300/4" alt="" />
<img class="lazy" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="http://lorempicsum.com/up/627/300/4" alt="" />
</div>
jQuery:
$.fn.lazyLoad = function(){
var lazy = $(this).find('img[data-src]');
$(lazy).each(function(index){
$(this).attr('src', $(this).attr("data-src"));
});
};
$('.slide').click(function(){
$(this).lazyLoad();
});
And a jsfiddle:
jsfiddle
Use <div> and background-image they load faster (at least perceived faster), but if you are concerned about accessibility and/or SEO, go with what you have already. I optimized the jQuery a little:
Use .lazy instead of [data-src] class selectors are faster than attribute selectors.
When getting or setting data-* attributes, it's better to use the newer way by using .data() instead of .attr().
The background-image property can be manipulated by the .css() method.
SNIPPET
$.fn.lazyLoad = function() {
var lazy = $(this).find('.lazy');
lazy.each(function(index) {
var data = $(this).data('src');
$(this).css({
'background-image': 'url(' + data + ')'
});
});
}
$('.slide').on('click', function() {
$(this).lazyLoad();
});
.lazy {
width: 627px;
min-height: 200px;
background-repeat: no-repeat;
background-size: contain;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slide">
<button>Click to load images</button>
<div class="lazy" data-src="http://lorempicsum.com/up/627/300/3"></div>
<div class="lazy" data-src="http://lorempicsum.com/nemo/627/300/4"></div>
<div class="lazy" data-src="http://lorempicsum.com/up/627/300/4"></div>
</div>
Why would you use base64 encoding for that? Encoded images are larger and so have a longer load time however say you are sending an email from a to b then you have to embed the image in the email. That is why it is possible to embed images in html. Emails have to be encoded to standards one of which is base64.
I'm trying to achieve the following:
I'm having simple html5 video streams running live on a website (Nr. 1-6). I would like, that the on click on one of these smaller thumbnails, that it will be displayed on top in the main bigger 'window'. I hope you understand what I mean. Is this even possible without any 3rd party tools?
That would be something like this (this example requires jQuery, just typing it out right here)
JS:
$(document).ready(function() {
$('.thumbnail').on('click',function() {
var videoSrc = $(this).attr('data-video');
$('#mainFrame').attr('src', videoSrc);
});
});
HTML parts needed:
<video id="mainFrame"></video>
<div class="thumbnail" data-video="URL_TO_VIDEO"></div>
<div class="thumbnail" data-video="URL_TO_VIDEO"></div>
This would assume you have the styling etc. already done
I am trying to build an email template in which i have to show some images to different mail client (eg.. outlook, thunderbird...). Now problem is when these clients does not allow to show image at that time broken image box is displaying which i don't want to display.
I had also refer
Refered link 1: How to remove borders around broken images in webkit?
Refered link [2]: input type="image" shows unwanted border in Chrome and broken link in IE7
Refered link [3]: How to stop broken images showing
but not able to find any proper output.
Note : I can not use div tag. I must have to use table tags.
CODE What I am using :
<table style="background:#fff; width:600px; margin:auto auto;">
<tr>
<td>
<a href="http://www.sampleurl.com">
<img src="http://sampleimageurl.com/sampleimage.png" height="55" width="198" />
</a>
</td>
<td style="text-align:right;"><a href="http://www.sampleurl.com" target="_blank">
<span style="font-family:Myriad Pro; color:#0d5497; font-size:20px;">www.sampleurl.com</span>
</td>
</tr>
<!--<tr>
<td colspan="2" style="height:1px; background: #0d5497;"></td>
</tr>-->
OUTPUT what i get.
use alt here for fallback
demo
html
<img src="abc" alt="image" />
css
img {
width:200px;
height:200px;
}
Alternatively, if you dont want to show any alt text, just give a blank space.
demo here
HTML
<img src="abc" alt=" " />
I know I'm late to the party but I didn't see a simple solution that used native javascript. Here is the solution I came up with
<img src="https://test.com/broken-image.gif" onerror="arguments[0].currentTarget.style.display='none'">
onerror calls a function, passing an error event as an argument. Because the argument is not actually defined as 'error' we need to get it from the arguments array that all functions have. Once we have the error we can get the currentTarget, our img tag, and sent the display to none.
I think you can use on error event on img.
here is a simple solution
Please pay attention that this script uses onDomReady event. In this case you should write:
<script type="text/javascript">//<![CDATA[
$(function(){
$('img').on('error', function () {
$(this).remove();
})
});//]]>
</script>
UPDATE
Why do you load images ? You can attach this image to email and show it via CID
You could any other element instead of and IMG and set the background-image using CSS. If that image is not found, you will not get the strange looking box.
<span style="background-image:url('http://sampleimageurl.com/sampleimage.png'); display:inline-block; width:198px; height:55px">
element with background
</span>
Sounds like a tough call not being allowed to use ALT text
If whoever is making this decision is convinced by a bit of styling you can do that e.g.
<img src="logo.jpg" width="400" height=”149″ alt="Company Name" style="font-family: Georgia; color: #697c52; font-style: italic; font-size: 30px; background:#ccffcc">
see http://jsbin.com/IcIVubU/1/
use this code block in your mail content to keep unrendered image as hidden.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<img id="imgctrl" src="imgs/sandeep11.png" onerror="$('#' + this.id).hide();" alt="Alternate Text" />
concept is.. use any CDN jquery reference then only jquery code will work. and I guess your src image path also should be some live url. if not then, it should be in attachment.
Please Click on "Show Remote content" to get remote urls into
thunderbird. this is security constraint of thunderbird. that's why
your images are not being loaded.
I know it is an old question but I found I had this problem too today (08 January 2020) and found a way to get around it.
I tested with the latest versions of Firefox and Chrome, I still could not find a solution for Safari.
Firefox:
For firefox you must add alt=" " note the space
Chrome:
For Chrome it must be alt="" note the empty space
The problem is that when I add the space the icon shows up on Chrome and disappears on Firefox, and vice versa when I remove it.
I added just a space because I did not want any text showing up on the image.
I did not have to add any of the following lines for it to work (I saw many solutions proposing some or all of them), but I left them in just in case
border: none;
outline: none;
border-image: none;
From there I guess it would be detecting a the browser in JavaScript and changing the alt attribut to " " or "".
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelectorAll('img').forEach(function(img){
img.onerror =function(){this.parentNode.removeChild(this);
})});
DEMO
you can remove img by javascript:
arr = document.getElementsByTagName("img");
for(i=0; i<arr.length; i++){
if(arr[i].src=="")
arr[i].parentElement.removeChild(arr[i]);
}
I have large, wide images within a portfolio page. The images are saved "progressive" and they load fine.
I was wondering if there's a way though to kind of preload those images to make them appearing faster and smoother. Or maybe there's a way to preload all the other pages and images into the cache so that at least all the following pages after the first appear smooth and fast? Whatever helps to make the pages load faster and smoother.
Any suggestions?
Each image consists of a variety of images, all of them within one wide image (prepared in PSD) and the visitor can shift left and right to call for the respective image to appear in the center.
Unfortunately sacrificing on the image quality or make them smaller is not an option here.
I know there are posts here on preloading images ad stuff but I can't find any that work with the image embedded in the HTML code.
Please have merci, I'm a CSS and Javascript novice, so the simpler the more likely I'll understand it. I'm afraid breaking up the images in single instances (make it a row of images instead of one whole image), place them in a floated div and change the respective Javascript code could be too challenging for me, right...? How else could I do that?
Appreciated!
Here's what I have (I guess it would be overkill to post all my HTML, Javascript and CSS here, I'll post some). The large images are placed within the HTML page and called via Javascript.
see here
<div class="ShiftGroup">
<div class="ShiftGroupC">
<div class="ShiftGroupI"><div id="ShiftGalleryFive"><img src="images/gallery_anzic1.png" width="3348" height="372" alt="imagegallery1" /></div></div>
<div class="ShiftGroupP" style="margin-left: -990px;"><div id="ShiftLeft" class="ShiftGroupD"><span class="pointer"><img src="images/arrowleft.png" width="78" height="50" alt="arrowsleft" /></span></div></div>
<div class="ShiftGroupP" style="margin-left: 341px;"><div id="ShiftRight" class="ShiftGroupD"><span class="pointer"><img src="images/arrowright.png" width="78" height="50" alt="arrowright" /></span></div></div>
and
gallery = document.getElementById('ShiftGalleryFour').style;
This is how we preloaded images in one of our projects:
preloadImages = function(imageIndex) {
// Finds div element containing index (1..n) and url of image
// (both stored as data attributes)
var image = $(".data .image[data-index=" + imageIndex + "]");
// Creates an image (just virtually) that is not embedded to HTML.
// Its source is the url of the image that is to be preloaded
var preloadedImage = $(new Image()).attr("src", image.attr("data-full-url"));
// Bind an event to the "virtual" image to start preloading next image when
// this one is done
preloadedImage.load(function() {
// Start preloading the next one
preloadImages(imageIndex + 1);
});
}
// Start preloading the first image
preloadImages(1)
In your case this solves only one part of the problem - preloading.
I see you include all images in html as img tags. If you want to achieve better performance, do not place any img tags in your html of the gallery. Just div tags that will become the future containers of your images. These divs may have indexes and contain data attributes with image urls (as seen in my example). When your page gets loaded, start preloading procedure. When an "virtual image" gets loaded. Create new image tag inside its container and start preloading the next image.
This will definitely cut off the download time of your page.
My example uses jQuery which simplifies the script. Pure javascript would be more complicated.
UPDATE:
This is how preloading example may work like.
HTML
Let's say you have 4 images and all of them has its container - a div in which individual image is to be placed.
<div class="images">
<div class="image" data-index="1" data-src="image_1_source_path"></div>
<div class="image" data-index="2" data-src="image_2_source_path"></div>
<div class="image" data-index="3" data-src="image_3_source_path"></div>
<div class="image" data-index="4" data-src="image_4_source_path"></div>
</div>
JavaScript
After the the document is loaded, preloading procedure may start. You start by preloading the first image. After this one is loaded, you append it to its container and trigger preloading of the next image. There is also return called if all images are loaded and no container is found.
preloadImages = function(imageIndex) {
var imageContainer = $(".images .image[data-index=" + imageIndex + "]");
return if imageContainer.length === 0
var preloadedImage = $(new Image()).attr("src", image.attr("data-full-url"));
preloadedImage.load(function() {
imageContainer.append(preloadedImage);
preloadImages(imageIndex + 1);
});
}
$(document).ready(function(){
preloadImages(1);
});
Hopefully you get the idea.