var img = new Image();
img.onload = () => {
console.log("loaded")
}
img.src = "https://b-ssl.duitang.com/uploads/item/201807/06/20180706150531_zFhZJ.thumb.700_0.jpeg"
Why would an image cached with the above code be re-requested when the background picture uses the same picture?
first post some of the experimental codes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.world{
background: url("https://b-ssl.duitang.com/uploads/item/201807/06/20180706150531_zFhZJ.thumb.700_0.jpeg");
width: 200px;
height: 200px;
background-size: 100% 100%;
}
.box{
display: none;
}
.a{
display: none;
}
.btn{
background: white;
}
</style>
</head>
<body>
<div class="hello " id="div">
</div>
<div class="a" id="a">
</div>
<button id="btn">Click</button>
<script>
window.onload = () => {
var btn = document.getElementById("btn");
var div = document.getElementById("div")
btn.addEventListener("click", () => {
div.classList.toggle("world")
})
var img = new Image();
img.onload = () => {
console.log("loaded")
}
img.src = "https://b-ssl.duitang.com/uploads/item/201807/06/20180706150531_zFhZJ.thumb.700_0.jpeg"
}
</script>
</body>
</html>
here is the http package for this code
theoretically, there is only one http request after preloading the cache
, but the results of several consecutive experiments are different
the experimental method is as follows:
grab the package to open preserve log
clear the cache
refresh and then wait a period of time for click and then refresh for a while and then wait for the event point click to repeat many times
-split line-
Note: I found that when a picture is loaded in this way, the same picture will still request again from the server
my operation mode is as follows:
1, new Image preloads the picture
2, and adds a class to a div after preloading. The code is as follows:
.world{
background: url("https://b-ssl.duitang.com/uploads/item/201807/06/20180706150531_zFhZJ.thumb.700_0.jpeg");
width: 200px;
height: 200px;
background-size: 100% 100%;
}
Why don"t background images read new Image preloaded images directly?