I have some homework to equip Lazy Loading into my java project using JSP-Servlet. I have not learned front-end development so I'm having difficulties accomplishing this task. When I run the web, it load all images but after i scroll it, the image is broken. I can not use any library in this project, is there any solution to fixed this?
This is my front-end code:
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages = document.querySelectorAll("img.lazy");
var lazyloadThrottleTimeout;
function lazyload () {
if(lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function(img) {
if(img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if(lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
});
img {
background: #F1F1FA;
width: 400px;
height: 300px;
display: block;
margin: 10px auto;
border: 0;
}
<%--
Document : shopping
Created on : Aug 26, 2018, 11:10:09 AM
Author : HiruK
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="tbl_machine.Tbl_machineDAO" %>
<%@page import="tbl_machine.Tbl_machineDTO" %>
<%@page import="java.util.List" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" type="text/css" href="css/table.css">
<link rel="stylesheet" type="text/css" href="css/center.css">
<script src="js/lazyLoading.js"></script>
</head>
<body>
<h1>Shopping here!</h1>
<c:set var="list" value="${sessionScope.IMAGELIST}"/>
<c:if test="${not empty list}">
<c:forEach var="item" items="${list}">
<img class="lazy"src="<c:url value="${item.picture}"/>"/>
</c:forEach>
</c:if>
<a href="member.jsp">Click here to back main page</a>
</body>
</html>