Skip to content

Commit

Permalink
feat: Loading resource update (#518)
Browse files Browse the repository at this point in the history
* feat: testing load options

* feat: change preload

* feat: remove preload, ineffective

* fix: lint issues

* feat: testing video loading thresholds

* doc: add notes on lazy load
  • Loading branch information
twhite313 authored Jan 15, 2025
1 parent 77f82ab commit dfd0ed6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
15 changes: 12 additions & 3 deletions eds/blocks/hero/hero.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,18 @@ export default function decorate(block) {
block.replaceChildren(...newChildren);

const imgCollection = block.querySelectorAll('picture > img');
imgCollection.forEach((img) => {
img.setAttribute('loading', 'eager');
});
const heroContainer = document.querySelector('main > .hero-container');
if (heroContainer && (heroContainer === heroContainer.parentElement.children[0]
|| heroContainer === heroContainer.parentElement.children[1])) {
imgCollection.forEach((img) => {
img.setAttribute('loading', 'eager');
img.setAttribute('fetchpriority', 'high');
});
} else {
imgCollection.forEach((img) => {
img.setAttribute('loading', 'lazy');
});
}

const blockTitle = block.querySelector('h1');
const blockParagraphs = blockTitle.parentElement.querySelectorAll('p');
Expand Down
12 changes: 9 additions & 3 deletions eds/scripts/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,9 @@ export function createAutoplayedVideo(sourceSrc, posterSrc = '') {
type: 'video/mp4',
muted: '',
},
source({ src: sourceSrc }),

/* add source element with data-src attribute to lazy load the video */
source({ 'data-src': sourceSrc }),
);

if (posterSrc) {
Expand All @@ -232,16 +234,20 @@ export function createAutoplayedVideo(sourceSrc, posterSrc = '') {
* IntersectionObserver to play or pause a video element based on its visibility.
* The video element will be played when the intersection ratio exceeds 0.8.
* Otherwise, the video element will pause.
* lazy loads the video source when the video is in view
*/
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0.8) {
if (entry.intersectionRatio > 0.4) {
if (!videoElem.src) {
videoElem.src = videoElem.querySelector('source').dataset.src;
}
videoElem.play();
} else {
videoElem.pause();
}
});
}, { threshold: [0, 0.8] });
}, { threshold: [0, 0.4] });

observer.observe(videoElem);

Expand Down

0 comments on commit dfd0ed6

Please sign in to comment.