I coded lazy loading for videos, background images and images but didn’t work on ios safari.
I want show the background images/images/video with IntersectionObserver method.
below codes are for background image and video.
JavaScript
x
18
18
1
<a href="#" id="comp-modal1" data-toggle="modal" data-target="#vidmodal" class="col-12 col-sm-3 align-self-center show-bkg lazy-bg lazy"
2
data-video="{{ get_template_directory_uri() . $video_path . $qt190}}"
3
data-srcset="{{ get_template_directory_uri() }}/assets/images/vid-images/show-bk.jpg" aria-label="background">
4
<div class="show-info">
5
<i class="fa fa-play-circle fa-3x" aria-hidden="true"></i>
6
<h3>QTech QT190 Journey</h3>
7
</div>
8
</a>
9
10
<video data-src="/wp-content/uploads/2019/03/Aristospray-QTech-Q5-2-minute-montage-v3-android-pad-compress.mp4"
11
poster="{{ get_template_directory_uri() }}/assets/images/vid-images/pistol-suction.jpg"
12
width="100%" height="auto"
13
class="lazy"
14
aria-label="video"
15
data-id="vid1">
16
</video>
17
18
and this is my JS =
JavaScript
1
72
72
1
2
3
const lazy ={
4
img:(img)=>{
5
img.src = img.dataset.src;
6
},
7
background:(bg)=>{
8
bg.style.backgroundImage = `url(${bg.dataset.srcset})`;
9
},
10
video:(vid)=>{
11
vid.load();
12
fetchVideoAndPlay(vid);
13
},
14
}
15
16
17
function fetchVideoAndPlay(video){
18
const preloadHolder = (document.querySelector(`#${video.dataset.id}`));
19
//console.log(video.dataset.src);
20
fetch(video.dataset.src)
21
.then(response=> {
22
video.setAttribute('data-src','');
23
return response.blob();
24
})
25
.then(blob=>{
26
video.src = URL.createObjectURL(blob);
27
video.muted = true;
28
preloadHolder.remove();
29
return video.play();
30
})
31
.then(()=>{
32
console.log('Played');
33
})
34
.catch( (e)=>{
35
console.error(e);
36
});
37
}
38
39
40
41
const lazyItems = [].slice.call(document.querySelectorAll('.lazy'));
42
const configInterSection = {root: null,rootMargin: '0px',threshold: [0]};
43
44
if ('IntersectionObserver' in window) {
45
let lazyObserver = new IntersectionObserver(function(entries){
46
// fire lazy loading
47
entries.forEach(function(item) {
48
if (item.isIntersecting) {
49
50
if(item.target.ariaLabel == 'background') lazy.background(item.target);
51
if(item.target.ariaLabel == 'image') lazy.img(item.target);
52
if(item.target.ariaLabel == 'video') lazy.video(item.target);
53
54
// remove & add classes
55
item.target.classList.remove('lazy');
56
item.target.classList.add('lazy-loaded');
57
58
//unboud
59
lazyObserver.unobserve(item.target);
60
}
61
});
62
}, configInterSection);
63
64
if(Array.isArray(lazyItems)){
65
lazyItems.forEach(function(lazy) {
66
lazyObserver.observe(lazy);
67
});
68
}
69
70
}
71
72
-Is there a way to modify this code in ios Safari?
- Also this codes didn’t work on the Firefox.
Advertisement
Answer
item.target.ariaLabel
is availbale in v8 engine (chrome). hence I changed it to item.target.getAttribute('aria-label')
now it works.