How to prevent some background-images caching - html

adding some random number it works, but only for img
<img src="example.jpg?377489229" />
Is there any way to prevent caching prp. background-image?
<div style="background-image: url(example.jpg )"></div>"

The same technique will work there.
<div style="background-image: url(example.jpg?377489229)"></div>
Assuming your server doesn't act differently with the presence of that GET param.
This will only break the cache once though, if you want it to always hit the server, you will need to use some different techniques.

To generate image urls with dynamic timestamp as query param You need at least JavaScript code that will dynamically add latest timestamp to background image url and make something like this:
someimage.jpg? (new Date()).getTime() => someimage.jpg?1479341018085
You can use this example:
function getNoCacheBgElements() {
return document.querySelectorAll('.no-cache-bg');
}
function loadBgImageForElement(element) {
element.style['background-image'] =
'url('+ element.attributes['data-background-image'].value + '?' + (new Date()).getTime() +')';
}
function loadBgImages() {
for(
var i = 0, elements = getNoCacheBgElements();
i < elements.length;
loadBgImageForElement(elements[i]), i++
);
}
window.onload = function() {
loadBgImages();
};
.size-100x100 {
min-width: 100px;
min-height: 100px;
}
.float-left {float: left;}
.margin-10 {margin: 10px;}
<p> These background images loaded dynamically every time You hit "Run code snippet". </p>
<div class="no-cache-bg size-100x100 float-left margin-10" data-background-image="http://lorempixel.com/output/abstract-q-c-640-480-8.jpg"></div>
<div class="no-cache-bg size-100x100 float-left margin-10" data-background-image="http://lorempixel.com/output/abstract-q-c-640-480-9.jpg"></div>
<div class="no-cache-bg size-100x100 float-left margin-10" data-background-image="http://lorempixel.com/output/abstract-q-c-640-480-10.jpg"></div>
</br>
<p> Check browser's network tab and You'll see that it requests for images on every page load. </p>

Related

Load image on hover over <a>

While I wasn't that concerned about it in the beginning, I noticed that my page size is about 9 MB (+/- 200 images). I want to somehow decrease this by only loading the image when the user hovers over the specific <a>, so that only that image is loaded (which should decrease the page size drastically).
The code below is what I'm using right now
<style>
div.img {
display: none;
position: absolute;
}
a:hover + div.img {
display: block;
}
</style>
<div>
Some Name
<div class="img">
<img src="http://sub.domain.com/somename.jpg" alt="Some Name" style="some styles">
</div>
</div>
I think it's possible with jQuery, but I don't know where to start.
Thanks in advance.
Well if you have around 200 images in your directory, when a client requests the webpage it is going to have to download the images to have them ready if you are using a single page layout. I would look into lazy loading just as Adam stated. If you can also I would suggest to try to compress the photos if you can to lower the file size if possible. Good luck!
I fixed my problem by adapting an existing pen-code to adjust my needs (using jQuery). It now works again in IE/Firefox
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function($) {
$('.trigger').mouseover(function() {
// find our span
var elem = $(this).siblings('span');
// get our img url
var src = elem.attr('data-original');
// change span to img using the value from data-original
elem.replaceWith('<img src="' + src + '" style="display:block;position:absolute;"/>');
});
$('.trigger').mouseout(function() {
// find our span
var elem = $(this).siblings('img');
// get our img url
var src = elem.attr('src');
// change span to img using the value from data-original
elem.replaceWith('<span data-original="'+src+'"></span>');
});
});
</script>
Hover over me to fetch an image
<span data-original="https://lorempixel.com/g/150/200/"></span>
you can put the image with no src attribute and put the specific src in the href of div or the image!
then use jquery to get the href of a or data-src of image and then give it to the image the code will be something like this:
<a class="image" href="the-src-of-the-image">
<img src="(leave this blank)">
</a>
and this is the jquery
jQuery(document).ready(function($){
$('.image').on('hover',function(){
var img_src = $(this).attr('href');
$(this).children('img').attr('src',img_src);
});
});

How can i change the innerHTML content when clicking on an image?

I'm quite new in coding, trying to educate myself because i'm interested. So, sorry if it's going to be a bit dumb question or not so specific or not really correct...
On my "practicing site" i'm having some navigation links, which are referring to different innerHTML contents (like different pages). I used the 'onClick' event to make them show up, for example like this:
<div class="nav" onClick="changeNavigation('a')">menu</div>
It works with texts perfectly, but my problem is that i don't know how to make the same with an image. So when i click on the image, i want to be redirected to that innerHTML page, like i did it with the text based button. I tried to do it like these two ways, but none of them worked.
<img src="picture.png" onClick="changeNavigation('a')" />
<div onClick="changeNavigation('a')"><img src="picture.png"></div>
Is it possible to make this with an image and the 'onClick' event? Or how else can i make this work?
By the way this is my script to make innerHTML show up:
<script>
function changeNavigation(id) {
document.getElementById('main').innerHTML = document.getElementById(id).innerHTML
}
</script>
I also tried to add my image an id that says 'main' like in the script this way, but with no result.
<img id="main" onClick="changeNavigation('f')" src="picture.png" />
Can you help me please? I would appreciate any answer, because i already searched about this and i didn't find anything that could've helped solve my problem and i'm really stuck right now.
(Sorry if my english isn't the best, it's not my native language.)
I have updated my answer to what you want. You need to the divs id you want to display as a parameter to the function you use for onclick. A sample is below.
var divs = ["Menu1", "Menu2", "Menu3", "Menu4"];
var visibleDivId = null;
function toggleVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.main_div{text-align:center; background: #00C492; padding:20px; width: 400px;}
.inner_div{background: #fff; margin-top:20px; height: 100px;}
.buttons a{font-size: 16px;}
.buttons a:hover{cursor:pointer; font-size: 16px;}
img {cursor:pointer}
<div class="main_div">
<div class="buttons">
<img src="http://www.clker.com/cliparts/J/g/2/D/p/I/one-hi.png" width="50px" onclick="toggleVisibility('Menu1');"> <img src="http://www.clker.com/cliparts/E/x/J/x/m/z/blue-number-two-hi.png" width="50px" onclick="toggleVisibility('Menu2');">
<img src="http://www.clker.com/cliparts/L/H/T/b/g/N/three-md.png" width="50px" onclick="toggleVisibility('Menu3');">
<img src="http://www.clker.com/cliparts/v/G/G/A/D/s/four-md.png" width="50px" onclick="toggleVisibility('Menu4');">
</div>
<div class="inner_div">
<div id="Menu1">I'm container one</div>
<div id="Menu2" style="display: none;">I'm container two</div>
<div id="Menu3" style="display: none;">I'm container three</div>
<div id="Menu4" style="display: none;">I'm container four</div>
</div>
</div>
You can just keep all of the sections as children of #main, and selectively show them when the section button in clicked. E.g.,
HTML
<nav>
<button type="button" data-index=0>Show one</button>
<button type="button" data-index=1>Show two</button>
<button type="button" data-index=2>Show three</button>
</nav>
<main id="main">
<section>One</section>
<section class="hidden">Two</section>
<section class="hidden">Three</section>
</main>
CSS
.hidden {
display: none;
}
JavaScript
const buttons = Array.from(document.querySelectorAll('button'));
const contentBlocks = Array.from(document.querySelectorAll('section'));
function hideSections (arr) {
arr.forEach(a => {
a.classList.add('hidden');
});
}
function showSection (index, sections) {
// Just a basic check, not exhaustive by any stretch
if (index !== undefined && sections !== undefined) {
hideSections(sections);
sections[index].classList.remove('hidden');
}
}
buttons.forEach(button => {
button.addEventListener('click', () => {
const contentBlocks = Array.from(document.querySelectorAll('section'));
const index = button.getAttribute('data-index');
showSection(index, contentBlocks);
});
});
Obviously you'll have to adjust your selectors for your use case, but Here's a pen
Here's a GitHub Gist pointing to some examples I created on JSFiddle based off of your specific use case (Stack Overflow doesn't let me post links to JSFiddle directly without including code here, but it's easier to follow along/experiment entirely in JSFiddle):
https://gist.github.com/andresn/f100386f06ee28e35bd83c62d9219890
More advanced stuff:
Ideally, you'd use what's called event delegation instead of adding an onclick to every anchor (DRY = Don't Repeat Yourself is good to always keep in mind while programming and so is KISS = Keep It Simple Silly). Here is a resource explaining event delegation:
https://davidwalsh.name/event-delegate
You can even take this further by preloading all your images so they load behind the scenes when the user first loads the page:
https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

CSS values from dynamic HTML attribute or class in order to avoid inline styles?

As we all know inline styles are not good practice and they are not compatible with e.g. the Content Security Policy.
This is what I want to achieve without inline styles:
<?php
$spacer_height = 390; // this is a dynamic value from user input could be any integer
?>
<div class="spacer" style="height:<?php echo $spacer_height; ?>"></div>
This is what I want:
HTML:
<?php
$spacer_height = 390; // this is a dynamic value from user input
?>
<div class="spacer spacerheight-<?php echo $spacer_height; ?>" data-height="<?php echo $spacer_height; ?>"></div>
External Stylesheet:
.spacer {
height: spacer_height + "px"; // this line is dummy code
}
Is where a way to achieve this with CSS only. No JavaScript. No Polyfill.
What I have already found is this 5 year old question: CSS values using HTML5 data attribute
However is there a solution meanwhile or is there a CSS solution not using attributes? Is there at least a solution for integers?
Edit: Even a working polyfill may be a welcome answer if there is no other solution.
As you can't do this CSS only (yet, since the attr() function only returns string value), here is a simple script that will do something similar what attr() does, though this parse the data and sets it dynamically using cssText.
Let me know if I got this right
window.addEventListener("load", function() {
var mb = isMobile();
var el = document.querySelectorAll('[data-css]');
for (i = 0; i < el.length; i++) {
var what = el[i].getAttribute('data-css');
if (what) {
what = what.split(',');
el[i].style.cssText = what[0] + ': ' + ((mb) ? what[2] : what[1]) + 'px';
}
}
});
function isMobile() {
//function that check if user is on mobile etc.
return false; // return false for this demo
}
html, body {
margin: 0;
}
div {
background-color: lightgreen;
padding: 10px 0;
height: auto;
box-sizing: border-box;
}
div ~ div {
margin-top: 10px;
}
<div data-css="height,60,30"></div>
<div></div>
<div></div>
<div data-css="height,60,30"></div>
<div></div>
Another option would be to run something server side, where you simply create the CSS rule and class and insert it into CSS file and markup respectively, before sending to the client
You might consider moving the dynamic part from being inline to being referenced in a <style>.
<style>
.spacer {
height:<?php echo $spacer_height; ?>
}
</style>
<?php
$spacer_height = 390; // this is a dynamic value from user input could be any integer
?>
<div class="spacer"></div>

Calling a class with symbolic name

EDIT: I would like to implement it with Jekyll, which (as far as I know) does not have PHP, jQuery, and so on...
I have a simple problem with CSS; it must have a simple solution but I just don't find it.
Suppose one has multiple divs with some classes:
<div class="cat">
<div class="dog">
<div class="bird">
<div class="snake">
...
and in a .css we want to style these 'pet' divs; the style is very similar from class to class (for instance we have some photos cat.jpg, dog.jpg... and want to show them). Can this be achieved by a somewhat symbolic method? Something like
div.pet{
width: 50px;
height: 50px;
background: url("/pictures/pet.jpg") no-repeat 0 0;
...
(but there is no class="pet" nor pet.jpg)
I would use sass:
div {
$list: "cat", "dog", "frog";
// generate classes for list elements
#each $element in $list {
&.#{$element} {
background-image: url('images/#{$element}.jpg');
}
}
}
That's not something you can do with CSS. CSS can only style objects and can't make other changes/additions/deletions of DOM objects.
But it is definitely something you can do with jQuery! If you know that you always have a class name class="cat" that is the same as the file name cat.jpg, you can do something like this:
$("div").each(function(){
var petClass = this.attr('class');
var petImg = petClass + ".jpg";
this.append("<img src='"+petImg+"' ... >");
});
Im not sure what your asking But as far as I understand you want to have some global setting for div elements and change the background image:
https://jsfiddle.net/shtjab2k/
Css
#pets > div
{
width:100px;
height:40px;
border:2px solid black;
float:left;
}
.cat
{
background-image: url("https://i.vimeocdn.com/portrait/58832_300x300.jpg");
}
.bird
{
background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/2000px-Solid_blue.svg.png");
}
html
<div id="pets">
<div class="cat "></div>
<div class="dog "></div>
<div class="bird "></div>
<div class="snake "></div>
</div>
The simplest, pure-css way to do this is this:
.dog, .cat, .bird, .snake {
width: 50px;
height: 50px;
background: url("/pictures/pet.jpg") no-repeat 0 0;
}
It doesn't matter that the background we provide doesn't exist, we'll replace it in the css for individual pet types:
.dog {
background-image: url("/pictures/dog.jpg");
}
It seems like you're looking for a way to do this in a single ruleset, which, unfortunately, is not possible. For that, you'd have to look into using Javascript or a CSS superset (see other answers on this post).
Otherwise, you can just write a couple more lines of css and set the background image for each pet type. =P
It isn't possible to add different images sources to the image tags with pure CSS. You may need to use JS, JQuery, PHP , etc.
You may do this using JavaScript/JQuery as follows :
Store all the image names in an array and then run a loop on-load(of page) to get images by using those array element(values).
Using jQuery, you may set img source like this:
$("img:nth-child(i)").attr('src', <new path from array[i th element]>);
The nth-child(i) means ith image.
Using Js, you may do this:
var images = [
'path/to/image1.png',
'path/to/image2.png',
'path/to/image3.png',
'path/to/image4.png',
'path/to/image5.png'
];
function loadImages(imgArr, targetId){
for(var i=0; i< imgArr.length; i++) {
console.log(imgArr[i]);
var img = new Image();
img.src = imgArr[i];
document.getElementById('output').appendChild(img);
}
}
loadImages(images);
You can also invode the loadImage() function from yout button:
<button onclick="loadImages(images)">Start</button>
Refer : JavaScript load Images in an Array

Load a low-res background image first, then a high-res one

I am trying to optimize the size of my site when it is being outputted to the client. I am down to 1.9MB and 29KB when caching. The issue is that the first load contains an image which is very unoptimized for mobile devices; it has a 1080p resolution.
So I am looking for a method that allows me to first load a low-res version (min.bg.jpg) and once the site has loaded, use a high-res version - or even one with a resolution close to the device being used (NNNxNNN.bg.jpg or just bg.jpg).
The background is set using CSS just like everyone would expect. Its applied to the body and the entire statement looks like this:
body {
background: url("/cdn/theme/images/bg.jpg");
color: white;
height: 100%;
width: 100%;
background-repeat: no-repeat;
background-position: 50% 50%;
background-attachment: fixed;
}
Now, I want to change that to use min.bg.jpg instead for the first load, and then something like this:
jQuery(function(){
jQuery("body").[...]
});
Which way do I go on asynchronously downloading the new background, and then inserting it as the new CSS background image?
To show some differences, here is an example of the main and mini version I am using for testing:
Ingwie#Ingwies-Macbook-Pro.local ~/Work/BIRD3/cdn/theme/images $ file *.jpg
bg.jpg: JPEG image data, EXIF standard
min.bg.jpg: JPEG image data, JFIF standard 1.01
Ingwie#Ingwies-Macbook-Pro.local ~/Work/BIRD3/cdn/theme/images $ du -h *.jpg
1,0M bg.jpg
620K min.bg.jpg
A bit late, but you can use this extremely simple solution:
You can put the two images in the css background:
background-image: url("high-res.jpg"),url("low-res.jpg");
The browser will display the low-res image fist, then display the high-res over the low-res when it has been loaded.
Let's try a basic one :
<img border="0"
style="background:url(http://i.stack.imgur.com/zWfJ5.jpg) no-repeat;
width:1920px;
height:1200px"
src="http://i.stack.imgur.com/XOYra.jpg" width="1920" height="1200" />
zWfJ5.jpg is the low-resolution version, and XOYra.jpg is the high-resolution version.
If there is a way to arrange the loading so the background-image displays first, this could be the simplest i can think of.
where low resolution 44k:
and high resolution is 1.16M
result :
jsFiddled here ( this needs a bigger image for loading comparison. )
Here's the method I use...
CSS:
#div_whatever {
position: whatever;
background-repeat: no-repeat;
background-position: whatever whatever;
background-image: url(dir/image.jpg);
/* image.jpg is a low-resolution at 30% quality. */
}
#img_highQuality {
display: none;
}
HTML:
<img id="img_highQuality" src="dir/image.png">
<!-- img.png is a full-resolution image. -->
<div id="div_whatever"></div>
JQUERY:
$("#img_highQuality").off().on("load", function() {
$("#div_whatever").css({
"background-image" : "url(dir/image.png)"
});
});
// Side note: I usually define CSS arrays because
// I inevitably want to go back and add another
// property at some point.
What happens:
A low-res version of the background quickly loads.
Meanwhile, the higher resolution version is loading as a hidden image.
When the high-res image is loaded, jQuery swaps the div's low-res image with the high-res version.
PURE JS VERSION
This example would be efficient for changing one to many elements.
CSS:
.hidden {
display: none;
}
#div_whatever {
position: whatever;
background-repeat: no-repeat;
background-position: whatever whatever;
background-image: url(dir/image.jpg);
/* image.jpg is a low-resolution at 30% quality. */
}
HTML:
<div id="div_whatever"></div>
<img id="img_whatever" class="hidden" src="dir/image.png" onload="upgradeImage(this);">
JAVASCRIPT:
function upgradeImage(object) {
var id = object.id;
var target = "div_" + id.substring(4);
document.getElementById(target).style.backgroundImage = "url(" + object.src + ")";
}
UPDATE / ENHANCEMENT (1/31/2017)
This enhancement is inspired by gdbj's excellent point that my solution results in the image path being specified in three locations. Although I didn't use gdbj's addClass() technique, the following jQuery code is modified to extract the image path (rather than it being hardwired into the jQuery code). More importantly, this version allows for multiple low-res to high-res image substitutions.
CSS
.img_highres {
display: none;
}
#div_whatever1 {
width: 100px;
height: 100px;
background-repeat: no-repeat;
background-position: center center;
background-image: url(PATH_TO_LOW_RES_PHOTO_1);
}
#div_whatever2 {
width: 200px;
height: 200px;
background-repeat: no-repeat;
background-position: center center;
background-image: url(PATH_TO_LOW_RES_PHOTO_2);
}
HTML
<div id="div_whatever1"></div>
<img id="img_whatever1" class="img_highres" src="PATH_TO_HIGH_RES_PHOTO_1">
<div id="div_whatever2"></div>
<img id="img_whatever2" class="img_highres" src="PATH_TO_HIGH_RES_PHOTO_2">
JQUERY
$(function() {
$(".img_highres").off().on("load", function() {
var id = $(this).attr("id");
var highres = $(this).attr("src").toString();
var target = "#div_" + id.substring(4);
$(target).css("background-image", "url(" + highres + ")");
});
});
What's happens:
Low res images are loaded for each of the divs based on their CSS
background-image settings. (Note that the CSS also sets the div to the intended
dimensions.)
Meanwhile, the higher resolution photos are being
loaded as hidden images (all sharing a class name of img_highres).
A jQuery function is triggered each time an img_highres photo
completes loading.
The jQuery function reads the image src path, and
changes the background image of the corresponding div. In the
example above, the naming convention is "div_[name]" for the visible divs
and "img_[same name]" for the high res images loaded in the
background.
I would normally optimise the image using Grunt or an online tool such as Tiny PNG to reduce the file size.
Then you could choose to defer the loading of the images, I found the following article helpful when it came to deferring images - https://www.feedthebot.com/pagespeed/defer-images.html
The article discusses using a base64 image for the initial loading and then deferring the loading of the high-quality image. The image mark up mentioned in the article is as follows...
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="your-image-here">
The JavaScript mentioned in the article is as follows...
window.addEventListener("load", () => {
const images = document.querySelectorAll("img");
for (let img of images)
if (img.hasAttribute("data-src"))
img.src = imgDefer[i].getAttribute("data-src");
});
I hope this helps.
On Ubuntu / Chrome 71, Milche's answer does not work consistently for me and the higher resolution image (via img src) often loads and resolves before the lower resolution image (via css background) even begins downloading.
My solution is to start with the lower res image as the src and use the Image class to create an unattached <img> instance with the high res image. Once it loads, then update the existing <img> source with the high res image source.
HTML:
<img id='my-image' src='low-res.png' alt='Title' width='1920px' height='1200px'>
JavaScript:
window.addEventListener('load', function() {
loadHighResImage(document.getElementById('my-image'), 'high-res.png')
})
function loadHighResImage(elem, highResUrl) {
let image = new Image()
image.addEventListener('load', () => elem.src = highResUrl)
image.src = highResUrl
}
Fiddle: https://jsfiddle.net/25aqmd67/
This approach works for lower res images that are simply scaled down as well.
All answers above mostly work with a little adjustment, but here is the way I think short and simple to kick off.
Note:
Uncomment the code load the high-resolution image for usage, a sleep function is just for simulating a slow network.
Actually, this method does not load 2 resources (low and high) simultaneous, but it's acceptable because low resource won't take much time to load.
Just copy whole code and run for a quick check.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<style type="text/css">
</style>
</head>
<body>
<!-- Load low res image first -->
<img style="width: 400px; height: auto;" alt="" src="https://s3-ap-southeast-1.amazonaws.com/wheredat/banner-low-quality/banner_20180725_123048.jpg" onload="upgrade(this)">
</body>
<script type="text/javascript">
function upgrade(image){
// After load low res image, remove onload listener.
// Remove onload listener.
$(image).prop("onload", null);
// Load high resolution image.
// $(image).attr('src', 'https://s3-ap-southeast-1.amazonaws.com/wheredat/banner/banner_20180725_123048.jpeg');
// Simulate slow network, after 1.5s, the high res image loads.
sleep(1500).then(() => {
// Do something after the sleep!
// Load a high resolution image.
$(image).attr('src', 'https://s3-ap-southeast-1.amazonaws.com/wheredat/banner/banner_20180725_123048.jpeg');
});
}
// Sleep time expects milliseconds
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</html>