Display two images with SRCSET at different screen size issue - javascript

I have looked over examples online, yet I believe I am overlooking something. I have two similar images that need to be rendered when the screen is at a different size. One image at 1440px screen size and one at 375px screen size. Right now with my code I have set the initial source to render the "mobile view" of the image, and with the srcset of the desktop view image at 1440w. When I load up live server it shows the desktop image, and not the initial source of the mobile view. So it seems to be working but missing a step.. any tips are greatly appreciated!
<img
class="future__container--img"
src="./images/illustration-editor-mobile.svg"
srcset="./images/illustration-editor-desktop.svg 1440w"
alt="illustration-editor-mobile"
/>
So when the browser first loads it is showing the desktop.svg, but when I set the browser to 375px it still displays the desktop.svg. I first had this written in javascript ..
const resizeEditiorImg = () => {
const reswidth = screen.width;
let image = document.querySelector(".future__container--img");
if (reswidth >= 1440) {
image.src = "../images/illustration-editor-desktop.svg";
} else {
image.src = "../images/illustration-editor-mobile.svg";
}
};
window.addEventListener("resize", resizeEditiorImg);
But the issue here is that when the browser first loads on desktop view, it is displaying the mobile image unless the user manually resizes the browser, which is what I believed at first. I hope this post makes sense!

This only work in resize browser because this code resizeEditiorImg
you need run this command resizeEditiorImg in your load page.
example
<body onload="resizeEditiorImg()">

Related

Load images separated from page loading

I am currently using lazy loading of images, in which all the images are loaded while page is loading and displayed after an image is loaded. In this method, page is shown loading at the tab section of browser till all the images are downloaded.
Now, I want to load the images separate from page loading. Like in google images, page is loaded within 1 second, and images are loaded one by one without showing the page loading in the tab of browser.
How can I achieve this?
So, the final question: How to first load the page fully, without downloading the images from server, and then download the image when the scroller is reached there. Till then, the image may be a grey box.
Loading an image when it comes into view.
Loading attribute
We could use native lazy loading with the loading attribute.
Here's a demo.
<div><img src="https://placeimg.com/410/410/any" loading="lazy" width="410" height="410"></div>
Currently, the latest version of Chrome, Firefox and Edge support native lazy loading.
Be aware that the distance threshold does vary in browsers.
Chrome
The distance threshold after which the deferred content will start
loading-in depends on factors including the current effective
connection type, and whether Lite mode is enabled. The distance is
chosen so that the deferred content almost always finishes loading by
the time it becomes visible.
Firefox
Tells the user agent to hold off on loading the image until the
browser estimates that it will be needed imminently. For instance, if
the user is scrolling through the document, a value of lazy will cause
the image to only be loaded shortly before it will appear in the
window's visual viewport.
Intersection Observer
We could also use the IntersectionObserver API to determine when your images are in view. This offers better compatibility across browsers and offers greater control for when and how our images load.
CodePen
HTML
<div>
<img src="data:,"
data-src="https://placeimg.com/410/410/any"
class="lazy"
alt=""
width="410"
height="410" />
</div>
JS
document.addEventListener("DOMContentLoaded", lazyLoad);
function lazyLoad() {
const images = [].slice.call(document.querySelectorAll("img.lazy"));
var config = {
// If the image gets within 500px in the Y axis, start the download.
rootMargin: "500px 0px",
// detect when visibility passes the 1% mark
threshold: 0.01
};
if ("IntersectionObserver" in window) {
const observer = new IntersectionObserver(showImage, config);
images.forEach(function (image) {
observer.observe(image);
});
}
}
function showImage(entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
const image = entry.target;
image.src = image.dataset.src;
observer.unobserve(image);
}
});
}
Existing libraries
There are also existing JavaScript libraries, such as lazySizes.

How to load all images before showing the page in React?

I am trying to find a more modern solution that doesn't use jQuery as I am using React (Gatsbyjs specifically).
I have a website with multiple image carousels that contain high res images.
The issue is the each image carousel only show one image at a time, so only when the user navigates to the next image does the image get fetched, this results in a choppy loading appearance.
I have tried researching online with onLoad and load event listeners but none seem to have worked so far because they only load the image that is currently being shown by the carousel, instead of all of the images in the carousel.
If there is a way to first load all the images, then set the state to true, and only after the state is true, then the rest of the DOM appears onto the screen, that would be perfect.
Any suggestions? Thanks.
Website in question: https://dev--yachtgamechanger.netlify.com/
As Lonnie Best said, I ended up using Promise.all() to capture the loads of the images.
Just in case anyone else want to check it out:
https://codesandbox.io/s/react-image-preload-ptosn
I guess that your lib is using lazy load approach. And it's really good when dueling with high res images.
You still can change the approach to load all the images before rendering the UI, by going into the carousel component, change the rendering behavior by checking whether all images be loaded or not before render.
Updated: Because you are using gatsby-image, so just use this property:
loading: "eager". For EX:
<Img
fixed={data.file.childImageSharp.fixed}
alt="Gatsby Docs are awesome"
loading="eager"
/>
https://www.gatsbyjs.org/packages/gatsby-image/
You can ensure that an image is pre-downloaded 100% well before it gets displayed to the screen.
Simply create an Image element and set its src property to the URL where the image is located. Then use the image's onload event to detect when it is ready for instant display.
// Image to Pre-Download:
var image = new Image();
console.time("Image Fully Downloaded in");
image.src = "https://www.nasa.gov/sites/default/files/thumbnails/image/pia24870.jpeg";
image.onload = function()
{
console.timeEnd("Image Fully Downloaded in");
console.log("Image is ready for viewing.");
clearInterval(interval);
progress.parentNode.replaceChild(btn, progress);
}
// Fake Progress Indicator:
let progress = document.createElement("progress");
progress.value = 3;
progress.max = 100;
progress.textContent = "Fake Progress";
document.body.appendChild(progress);
let interval = setInterval(()=>
{
if (progress.value === 99)
{
progress.value = 0;
}
else
{
progress.value = progress.value + 1;
}
},50)
// Button to Replace Progress Indicator:
let btn = document.createElement("button");
btn.textContent = "View Entire Image Instantly";
btn.addEventListener('click',function()
{
this.parentNode.replaceChild(image, this);
});
img { max-width: 100%; }
<p>Only after the image is completely downloaded, will you see the button to view it:</p>
Based on this concept, you could pre-load/queue as many images as you like into image objects, so that they are ready to be displayed instantly (well before the user decides to view the next image). Here's an example where I'm switching between preloaded images automatically (so fast that it looks like an animated gif -- but it is actually 27 separate images from 27 different URL locations): See statue example and view source.

Resize Replace logo Function clashing with navigation

So I'm a graphic designer with next to no coding knowledge, and want to learn. My friend and partner who is a web developer is away.
I am trying to replace a logo on our responsive site when the dimensions are under a certain amount of pixels or when a mobile view is displayed.
Got half of it working, on scroll down but then when adding this bit to try and have resize of browser which changes the navigation bar, the nav bar misbehaves and becomes a big static block.
Tried firebug and got stuck.
$(window).resize(function()
{ if($( window ).width()<750){ img.src = img.dataset.scroll; // set the scroll image
}
else
{ img.src = img.dataset.orig; // set the original image back
}
});
don't use javascript for this, but css #media queries: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

Issue with high resolution images in chrome(windows) loading from javascript

I am having a problem with a site. My problem is I am loading several images progressively - starting with a small resolution image for fast loading I am then ajaxing a bigger image in (normally the original size that a user uploads).
The code below works perfectly. HOWEVER when done on chrome on windows. if the bigger image is a really high res (lets say 4400 x 4000). The screen would go white and the image would disappear. The white bursts out of the container (which has overflow:hidden) on it and covers the screen. Only the elements with a higher z-index over the image displays.
If I inspect the element that is white. It shows that it is the element, and the image is loaded - the URL is fine and if I click the image to open in another tab it loads fine.
Does anyone have any idea why this is happening?
if(href){
var img = document.createElement('img');
img.className = 'openLBFullView hidden';
img.onload = function(){
loadBiggerImg(this);
};
$(img).data('url',$currentImg.data('url'));
img.src = href;
img.id = 'my-image';
}
var loadBiggerImg = function(img){
var originalImg = $('#my-image');
//append the img to the document
originalImg.before(img);
// append original styles and classes to new image
$(img).attr('style',originalImg.attr('style'));
$(img).attr('class',originalImg.attr('class'));
// fix for windows IE adding attributes
$(img).removeAttr('width').removeAttr('height');
//fade in new image over the top and remove old one
$(img).fadeIn(200,function(){
originalImg.remove();
});
}
One of the possible solutions - large images dont render in chrome
This not neccesarily will fix your issue though - I'd try using lowres jpegs scaled to highres and preload big one - once loaded fade lowres one and show the big one (in a way fake the progressive JPEG) - Hope that helps man.

Mobile App "unable to load previous operation due to low memory" after loading image?

I have a simple mobile app. It starts by prompting the user to select an image which is then loaded locally via the following code and displayed on a canvas:
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
console.log(evt);
var ctx = document.getElementById("myCanvas").getContext('2d'),
img = new Image(),
f = document.getElementById("uploadbutton").files[0],
url = window.URL || window.webkitURL,
src = url.createObjectURL(f);
img.src = src;
lastImage = img;
img.onload = function()
{
window.requestAnimationFrame(function(){
var w = window.innerWidth;
var h = window.innerHeight;
ctx.clearRect(0, 0, w, h);
ctx.drawImage(lastImage, 0, 0);
//url.revokeObjectURL(src);
});
}}
In my web browser and on my phone, the image is loaded and displayed in a canvas properly, however I have heard from a user who was running it on a Razr Maxx HD with Google Chrome, that they would receive "Error: unable to load previous operation due to low memory." I suspect that this issue cannot be solved by first reading in the image and then scaling it prior to displaying because the full image will have already been loaded into memory even if not displayed. Is there any way to load a scaled version of an image into memory without first loading the entire thing? Any idea what is causing this issue as I am able to load massive images on my Galaxy S3 in chrome and the Galaxy S3 has the same amount of RAM as the Razr Maxx HD?
It may depend on which applications the user is running as to how much memory is available.
One solution is to have the application request the image with certain width and the server can return a scaled image, which should reduce memory requirements.
I have had the same problem on my Samsung Galaxy S4. I have found the solution on my phone and I have had no issues since:
Go to the Settings on your phone.
Select More in the top right task item.
Scroll to Developer Options. - If you don`t have developer options enabled follow steps 1 & 2, Then scroll down to about device and click on it. The phone information should be displayed and you should scroll down till you get to Build Number. The next thing to do is click on Build Number several times... ( Each time you click on it an info bar will be displayed telling you how many clicks are needed for Developer options. When you have clicked BN several times then DO will now be open and we can continue with the above.
If you have clicked into Developer Options successfully then you must scroll down to the apps options near the bottom of D.O menu.
If ( Do not keep activities) is selected then be sure to untick it making sure the box has no tick in it as it will end every app or running operation as soon as it leaves the page, Hence the reason photos wont load up to Facebook etc. If this is done correctly then you should now be able to upload photos.

Categories