Tiny image placeholder; multiple base64 or single 1x1gif - html

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.

Related

Is there a css option that links an html image to itself?

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);
});
});

preload large gallery/slider images in HTML

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.

Rendering SVG in a web page

I have a web page in which i need to show SVG logos. This is quite easily possible in the latest browsers, but I need to make it compatible with older browsers too. Some how I need to display an alternate image to the user if the browser does not support SVG.
I have come across a method called HTTP-content negotiation, but how can I implement it to get the desired result?
I tried the <object> tag but it does not seem to work with IE and is very hard to style when tried with Firefox.
I'd implement this client side with the help of Modernizr. Given a markup such as...
<!-- Start with bitmaps because
they will show up in all browsers even
if javascript is not enabled -->
<img src="logo1.png" class="logo" />
<img src="logo2.png" class="logo" />
<img src="logo3.png" class="logo" />
<img src="logo4.png" class="logo" />
You can do...
$(document).ready(function(){
if (Modernizr.svg){
$('.logo').each(function(){
var src = $(this).attr("src");
var svg = src.substr(0, src.lastIndexOf('.')) + ".svg";
$(this).attr("src", svg)
})
}
})

html code for fading pictures one after another

I am a novice site builder. I have photos that I would like to put on my website and I would like to have them on a continuous transition one after the other. Could someone provide me with an HTML code where all I have to do in include the name of the pictures that I already have on file. They are different sizes, but when they transition in, I would like t have them the same size as well. They are in jpg format.
Thanks to anyone that can help with this?
You want to use jQuery for this so it will be much easier... I suppose you have HTML looking somthing like this (simplified):
<div class="images">
<img src="..." />
<img src="..." />
<img src="..." />
...
</div>
There are many image sliders out there with all kinds of functionality but if fading is all you need then writing a few lines of code may be easier.
Do something like this (using jQuery):
$(function() {
var images = $(".images img").hide();
var current = 0;
setInterval(function() {
var next = ((current + 1) % images.length);
images.eq(current).fadeOut();
images.eq(next).fadeIn();
current = next;
});
});
Don't forget to set CSS style to:
.images
{
position: relative;
}
.images img
{
display: none;
position: absolute;
}
This is a working example that rotates images every 5 seconds.
What you're looking for isn't HTML code, but Javascript (or CSS) code. I suggest you look up tutorials on how image sliders and galleries work and are structured. It is especially simple with the jQuery Javascript library.
I have looked up a couple of links of simple sliders and galleries you can try to understand and implement:
http://www.sohtanaka.com/web-design/automatic-image-slider-w-css-jquery/
http://www.tripwiremagazine.com/2010/10/20-stunning-jquery-image-sliders-and-tutorials-for-creating-your-own.html

Is there a way to designate multiple image sources in HTML/JavaScript?

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...