I am unable to get my images to lazy load with JavaScript. For some reason, the images just do not show up at all when I change the html from src to data-src. Then when I use an intersectionObserver to lazy load images, I can't get any images to show up on the page. Attached is my html, css and JS code;
html:
<div class="photo__container photo__container--one">
<img
data-src="portrait/1-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
<img
data-src="portrait/2-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
<img
data-src="portrait/3-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
</div>
CSS:
.img-vertical-lazy {
height: 70rem;
width: auto;
}
JS:
const lazyImages = document.querySelectorAll('.img-vertical-lazy');
const appearLazy = {
threshold: 0.1
};
const lazyLoading = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
entry.target.src = entry.target.getAttribute('data-src');
lazyLoading.unobserve(entry.target);
});
}, appearLazy);
lazyImages.forEach(image => lazyLoading.observe(image));
There are several ways to do that but it depends on your purpose of using lazy loading. In most cases, it is for SEO (i.e. for fast page loading).
If you are lazy loading images only for a fast page speed score then you can add this code to your page.
Here is a working example:
An image will be loaded when you scroll inside div.
<html>
<body>
<div id="mydiv" style="width:500px;height:300px;overflow:scroll;">
<h1>Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced</h1>
<div class="photo">
<img data-src="https://images.freeimages.com/images/small-previews/648/bs-04-1255720.jpg"/>
</div>
<h2>Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced image.Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced image.</h2>
</div>
<script>
var sw = 0;
document.getElementById('mydiv').onscroll=function(){
if(sw==0){
sw=1;
const lazyImages = document.querySelectorAll('img');
for (let i = 0; i < lazyImages.length; i++) {
lazyImages[i].src = lazyImages[i].getAttribute('data-src');
}
}
}
</script>
</body>
</html>
Tip: use window.onscroll to apply effect on whole webpage
Related
I am creating a web portfolio and I am using different photos/images for a responsive web page. But I am receiving the same error and I can not find the solution
.The reason I am using two different sets of images is that I am having vanilla javascript code for carousels but I am open to a different solution.
I named images so they could be added thru the for loop for example the first image is called img1.jpg, the second is named img2.jpg, etc.
function changeSource() {
const Images = document.querySelectorAll('.slides img');
for (let i = 1; i < Images.length; i++) {
Images[i].src = "../Assets/square/img" + i + ".jpg";
}
}
error message: 1 GET localhost:82/Assets/square/img6.jpg 404 (Not Found)
Here is the HTML markup
<images>
<section class="slides">
<img src="Assets/home/img4.jpg" id="lastclone">
<img src="Assets/home/img1.jpg">
<img src="Assets/home/img2.jpg">
<img src="Assets/home/img3.jpg">
<img src="Assets/home/img4.jpg">
<img src="Assets/home/img5.jpg">
<img src="Assets/home/img1.jpg" id="firstclone">
<img src="Assets/home/img2.jpg">
</section>
</images>
<script src="js/load.js"></script>
<script src="js/script.js"></script>
<script src="js/resize.js"></script>
I want to display a gif image until the website is completely loaded.
Once I click button (onclick=window.open) a new page opened but is blank and the gif is only appearing once the website is loaded.
I want once clicking the button a new page opened and showing immediately the gif and disappear once the page is loaded
Can anyone help me, what I’m doing wrong or what is missing to load the gif when the page is loading? Here is my code, thank you so much
land.php file:
<button type="button"
onClick="window.open('./gremo.cfm ',
toolbar=no,
menubar=no,
scrolling=yes,
scrollbars=yes
')">
</button>
gremo.php file:
<head>
<script type="text/javascript">
function showHide(elementid){
if (document.getElementById(elementid).style.display == 'none'){
document.getElementById(elementid).style.display = '';
} else {
document.getElementById(elementid).style.display = 'none';
}
}
window.onload = function () { reSizeTextarea(); showHide('loadingd'); }
</script>
</head>
<body>
<div id="loadingd" align="center">
<br/><br/><br/><img src="./loading.gif">
</div>
</body>
Note that when you are running locally, resources are loading fast.. very fast
Don't forget to use your developer tools and configure network throttling (to simulate a slower connection). That should simulate a "real" scenario and let you test your code better
Here is a screenshot from chrome... enjoy!
When you have a lot of content, it will take time to load. The image will show and than hide when the onload event happens. Now run it again, the content is cached and loading will take no time at all.
So load time depends on what there is to load/render, how it is loaded, and if it is cached or not.
window.onload = function () {
document.getElementById("loading").remove()
document.querySelector(".content").removeAttribute("hidden")
}
[hidden] {
display: none
}
#loading {
width: 300px;
}
<img id="loading" src="https://media.giphy.com/media/3o7bu8sRnYpTOG1p8k/source.gif" />
<div class="content" hidden>
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/100/100" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/400/400" />
<img src="http://placekitten.com/500/500" />
</div>
In your example, you have nothing that takes time to load other than the loading image. So as soon as your image is loaded, the window.onload is triggered. That is why it flashes.
If you want the image to show, you can add some logic saying if I have not been here for X seconds, than wait....
var startTime = new Date()
window.onload = function () {
var loadTime = new Date()
var diff = loadTime - startTime;
if (diff > 5000) {
toggleLoad()
} else {
window.setTimeout(toggleLoad, 5000 - diff)
}
}
function toggleLoad () {
document.getElementById("loading").remove()
document.querySelector(".content").removeAttribute("hidden")
}
[hidden] {
display: none
}
#loading {
width: 300px;
}
<img id="loading" src="https://media.giphy.com/media/3o7bu8sRnYpTOG1p8k/source.gif" />
<div class="content" hidden>
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/100/100" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/400/400" />
<img src="http://placekitten.com/500/500" />
</div>
To ensure the loading gif loads fast, on the parent page, you probably want to preload it
var img = new Image()
img.src = "your.gif"
Given Script load data from specific div of external source on click. Now trying to add div class when loading content like image and text. I mean when contents loads new classes will auto added with <div class="images"> img</div> and <div class="summery"> text text text</div>
HTML:
<button class='btn'/>
<div id="load-here"></div> <!-- Load Here -->
</body>
Script:
$(function() {
var page = null;
var counter = 0;
function getNext() {
// Grab the next element from the array of date-outer divs and copy it to the .content div
if (counter >= page.length)
return;
var elm = $(page[counter]).clone();
elm.find('script').remove(); // Remove script tags in the div
elm.appendTo('#load-here');
counter++;
}
$('button.btn').click(function(e) {
if (page === null) {
page = false; // Prevents the request from being made twice
$.get('http://test-html-site.blogspot.com/search/label/', function(data) {
page = $(data).find('article.post.hentry');
getNext();
});
} else if (page !== false) {
getNext();
}
});
});
HTML Structure of external site: Given script load .date-outer per click. Means it load data form external site/link on click.
<body>
<div class="blog-posts hfeed">
<div class="date-outer">
Contecnt 1: img, text </div>
<div class="date-outer">
Contecnt 2: img, text </div>
<div class="date-outer">
Contecnt 3: img, text </div>
</div>
</body>
My question is when data loading, want to add custom class to image and text using given script. This is the example site.
I've been looking around much today and spend a few hours trying to get something done. For a client I am creating a slideshow with a lightbox when clicked on an image. The slideshow and lightbox both work, but I don't get the right image in the lightbox yet.
This is the code that loads the slideshow and when clicked on an image opens the lightbox.
(The images for the slideshow get loaded by a php script and turned into a Javascript array)
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
}
</script>
<div style="width: 170px; height: 160px">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style. display='block'">
<img id="slideshow" src="" />
</a>
<div id="light" class="white_content">
<img id="lightImg" src="" />
<script>
var image = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", image);
</script>
I now try to create a variable named "image"and let this contain the src of the current image in the slideshow. So I can load this to the image in the lightbox.
Hopefully some one can give me some usefull tips. I am pretty new in the Javascript language.
The script for the slideshow came from: http://www.javascriptkit.com/javatutors/externalphp2.shtml
Regards Koen.
These days there really is no excuse for using obtrusive Javascript (Stuff inside your HTML attributes, ideally it should be in an external file. http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
I have done you the favour of cleaning up your code a bit, and changed it where you seemed to be going wrong. As DotNetter has already pointed out it would be sensible to use jQuery in this instance, as it really does simplify things. However, I'm going to assume that for some reason you want it in plain js. Below is a simplification of the code that you posted with the correct change.
<style type="text/css">
.wrapper {
width: 170px;
height: 160px;
}
</style>
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/" + galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
</script>
<div class='wrapper'>
<img id="slideshow" src="" />
<div id="light" class="white_content">
<img id="lightImg" src="" />
</div>
</div>
Before, you were getting the src of the current image when the page loaded, you need to be getting the src of the image when the user clicks on the
I have two large image files in a div on a page that take several seconds to load. How can I hide the loading content while a "loading gif" appears and then have the content appear once it has fully loaded?
I don't really know anything about javascript but I tried using this code. It did half of what I wanted it to do. The "loading gif" worked but the problem was that the content was visible as it was loading.
http://aaron-graham.com/test2.html
<div id="loading" style="position:absolute; width:95%; text-align:center; top:300px;">
<img src="img/parallax/ajax-loader.gif" border=0>
</div>
<script>
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
function init()
{
if(ns4){ld.visibility="hidden";}
else if (ns6||ie4) ld.display="none";
}
</script>
Any help would be greatly appreciated!
Use jquery, with code like:
$(document).ready(function(){
$('#pic1').attr('src','http://nyquil.org/uploads/IndianHeadTestPattern16x9.png');
});
With the html like:
<img id="pic1" />
It works by running when document's ready function is called (which is called after the DOM and other resources have been constructed), then it will assign the img's src attribute with the image's url you want.
Change the nyquil.org url to the image you want, and add as many as needed (just don't go overboard ;). Tested Firefox 3/chrome 10.
Here is the demo: http://jsfiddle.net/mazzzzz/Rs8Y9/1/
Working off your HTML structure I added a notifyLoaded class for the two images so you can watch for when both have loaded via an onload event. Since css background images don't get that event I've created a hidden img using the background's path so we can test when that image is loaded
HTML:
<div id="loading">
<img src="http://aaron-graham.com/img/parallax/ajax-loader.gif" border="0" />
</div>
<div id="vertical">
<div>
<div class="panel">
<img class="notifyLoaded" src="http://aaron-graham.com/img/parallax/tile3.png" />
</div>
</div>
</div>
<div id="imgLoader">
<img class="notifyLoaded" src="http://aaron-graham.com/img/parallax/deepspace3.jpg" alt="" />
</div>
You have reference to jQuery in your page already so I've replaced your script to the following.
jQuery:
$(document).ready(function() {
var $vertical = $('#vertical');
var $imgs = $('.notifyLoaded');
var imgCount = $imgs.length;
var imgLoadedCount = 0;
$vertical.backgroundparallax(); // Activate BG Parallax plugin
$imgs.load(function() {
console.log(this);
imgLoadedCount++;
if (imgCount == imgLoadedCount) {
// images are loaded and ready to display
$vertical.show();
// hide loading animation
$('#loading').hide();
}
});
});
I've also set #Vertical to a default display:none; which gets changed when images have loaded
CSS:
body {background-color:black;}
#loading {position:absolute;width:95%;text-align:center;top:300px;}
#vertical {display:none;background-image: url('http://aaron-graham.com/img/parallax/deepspace3.jpg');background-position: 0 0;height: 650px;width: 900px;overflow: auto;margin:35px auto auto auto;}
#vertical > div {margin: 0;color: White;}
#vertical .panel {padding: 100px 5%;margin-left:40px;height: 3363px;}
#imgLoader {display:none;}