如何使用 JavaScript 预加载图像?
preload 属性指定作者认为页面加载时媒体文件应该如何加载。preload 属性允许作者向浏览器提供有关加载页面需要花费多少时间的提示,这将带来最佳的用户体验。
Preload 还告诉浏览器您希望尽快加载的关键资源。这对于不容易感知的资源(例如样式表中包含的字体、背景图像或从脚本加载的资源)尤其有用。
使用preload 在这里很有帮助,因为图像会提前开始加载,并且在浏览器需要显示它时很可能已经存在。
JavaScript 中有几种类型的图像预加载。
示例 1:在 JavaScript 中使用事件侦听器
在以下示例中,我们正在预加载图像。如果图像在浏览器中完全加载,则它将显示图像。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<p>onload Event</p>
<img id="img1" src="https://tutorialspoint.com/java/images/java-mini-logo.jpg" style="max-width: 50%;">
<img id="img2" src="https://tutorialspoint.com/javafx/images/javafx-mini-logo.jpg" style="max-width: 50%;" >
<script>
const img1 = document.getElementById("img1");
const img2 = document.getElementById("img2");
img1.addEventListener("load", function(){
alert("first image is loaded");
});
img2.addEventListener("load", function(){
alert("second image is loaded");
})
</script>
</body>
</html>
示例 2
在以下示例中,我们创建了两个函数,第一个是 preloader(),第二个是 addLoadEvent(),并使用了 onload 事件侦听器。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<img id="img1" src="https://tutorialspoint.com/java/images/java-mini-logo.jpg" style="max-width: 20%" />
<img id="img2" src="https://tutorialspoint.com/javafx/images/javafx-mini-logo.jpg" style="max-width: 20%" />
<script>
function preloader() {
if (document.getElementById) {
document.getElementById("img1");
document.getElementById("img2");
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
};
}
}
addLoadEvent(preloader);
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP