Prevent images from loading
If you render the HTML on the page, even if it's hidden, it's going to load. If you want images to load only when they're needed, you're going to have to dynamically set the source (src) on the image tag in javascript.
Edit 1: The script you referenced merely checks to see how far you've scrolled the page down and then determines which images are visible (or almost visible) by checking their top -- see the $.belowthefold and $.rightoffold extensions.
The example works great when the images are all the same size because their containers can also be the same size and you won't get any odd page resizing behavior when you lazy load them. If your images' heights and widths vary, you may get some odd results.
Edit 2:
<script type="text/javascript" charset="utf-8">
$(document).ready( function() { $("img").removeAttr("src"); } );
</script>
<img src="Chrysanthemum.jpg" />
<img src="Desert.jpg" />
<img src="Hydrangeas.jpg" />
<img src="Jellyfish.jpg" />
<img src="Koala.jpg" />
<img src="Lighthouse.jpg" />
<img src="Penguins.jpg" />
<img src="Tulips.jpg" />
How to Prevent image from loading that comes from server side
You can hide original image and use a place holder image in your loop and call original image onload
function to hide place holder image and show actual image
<img src="placeholderurl" id="placeholder_{{i}}" >
<img [src]="category?.Picture1" class="hidden" id="original_{{i}}" (load)="onImageLoad(i)">
you onimageload function will look like
onImageLoad(idx){
var orginalEle=document.getElementById(`original_${idx}`)
var placeHolderEle=document.getElementById(`placeholder_${idx}`);
placeHolderEle.classList.add('hidden');
orginalEle.classList.remove('hidden');
}
Demo
How to prevent browser from loading images in mobile viewport
You can either use your picture as a background-image.
It will only be loaded if the media-queries are accepted, so for mobile devices the picture don't load and for desktop versions the picture will load.
The downside to this is that Google won't index your picture in for example Google Images but if your picture doesn't have a benefit for the user/text it isn't bad.
The other option is that you use
<picture>
<source media="(min-width: 768px)" srcset="your-desktop-picture.jpg">
<source srcset="your-mobile-picture.jpg">
<img src="fallback-for-old-browsers.jpg" alt="Sample Image">
</picture>
You can use picture to choose between different images, your mobile-picture could also be one pixel big, but it is important to have one, so the browser won't choose the desktop picture.
In summary i would recommend the solution with the css media-queries because it's easier and your picture isn't necassary for text understanding.
Does display:none prevent an image from loading?
Browsers are getting smarter. Today your browser (depending on the version) might skip the image loading if it can determine it's not useful.
The image has a display:none
style but its size may be read by the script.
Chrome v68.0 does not load images if the parent is hidden.
You may check it there : http://jsfiddle.net/tnk3j08s/
You could also have checked it by looking at the "network" tab of your browser's developer tools.
Note that if the browser is on a small CPU computer, not having to render the image (and layout the page) will make the whole rendering operation faster but I doubt this is something that really makes sense today.
If you want to prevent the image from loading you may simply not add the IMG element to your document (or set the IMG src
attribute to "data:"
or "about:blank"
).
How to prevent partially loaded images from displaying?
One way would be to give them a class that gives them opacity: 0
so they don't show:
<img src="/path/to/image" class="loading">
And in CSS:
.loading {
opacity: 0;
}
In head
, we override that if JavaScript is disabled (so we're not unfriendly to non-JavaScript visitors):
<noscript>
<style>
.loading {
opacity: 1;
}
</style>
</noscript>
...and then in code at the bottom of your page, find all your images and remove the class when they've loaded, and...(see comments):
(function() {
// Get an array of the images
var images = Array.prototype.slice.call(document.querySelectorAll("img.loading"));
// Hook their load and error events, even though they may have already fired
images.forEach(function(image) {
image.addEventListener("load", imageDone.bind(null, image));
image.addEventListener("error", imageDone.bind(null, image)); // Could handle errors differently
});
// Check to see if any images are already complete
checkImages();
function imageDone(img) {
img.classList.loading("remove");
images = images.filter(function(entry) { entry != img });
}
function checkImages() {
images.forEach(function(image) {
if (image.complete) {
imageDone(image);
}
});
if (images.length) {
// Check back in a second
setTimeout(checkImages, 1000);
}
}
})();
That's a belt-and-braces approach. It proactively checks to see if images have finished loading, and also reactively handles the load
and error
event of images. In theory, we shouldn't need the setTimeout
, and you might do testing without it, but...
Notice how once an image is complete, we remove the class so it's visible.
JQuery: Prevent images from loading when parsing HTML
Rather than using a regular expression, it would probably be a lot more elegant to use DOMParser
to fix the HTML string - just iterate over elements that match the img[src]
selector, set their data-img
, and remove their src
:
const useLater = [];const htmlStr = `<div><img src="foo"></div><div><img src="baz"><img src="baz"></div>`;const doc = new DOMParser().parseFromString(htmlStr, 'text/html');doc.querySelectorAll('img[src]').forEach((img) => { const src = img.getAttribute('src'); img.setAttribute('data-img', src); img.removeAttribute('src'); useLater.push(src);});console.log(doc.body.innerHTML);
Related Topics
React.Js: Onchange Event for Contenteditable
Event Delegation VS Direct Binding When Adding Complex Elements to a Page
Positive Look Behind in JavaScript Regular Expression
Associative Array Versus Object in JavaScript
How to Implement Prepend and Append with Regular JavaScript
Automatic Semicolon Insertion & Return Statements
Injecting JavaScript Variable Before Content Script
How to Set State of Response from Axios in React
Javascript: Clear All Timeouts
JavaScript Regular Expressions and Sub-Matches
Check If Jquery Has Been Loaded, Then Load It If False
Sorting Objects by Property Values
Math Random Number Without Repeating a Previous Number