-
Notifications
You must be signed in to change notification settings - Fork 98
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Moves embed-optimizer-lazy-load script to js file
- Loading branch information
1 parent
ecceec8
commit 6bc9408
Showing
2 changed files
with
57 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/** | ||
* Lazy load embeds | ||
* | ||
* When an embed block is lazy loaded, the script tag is replaced with a script tag that has the original attributes | ||
*/ | ||
|
||
const lazyEmbedsScripts = document.querySelectorAll( | ||
'script[type="application/vnd.embed-optimizer.javascript"]' | ||
); | ||
const lazyEmbedScriptsByParents = new Map(); | ||
|
||
const lazyEmbedObserver = new IntersectionObserver( | ||
( entries ) => { | ||
for ( const entry of entries ) { | ||
if ( entry.isIntersecting ) { | ||
const lazyEmbedParent = entry.target; | ||
const lazyEmbedScript = | ||
/** @type {HTMLScriptElement} */ lazyEmbedScriptsByParents.get( | ||
lazyEmbedParent | ||
); | ||
const embedScript = document.createElement( 'script' ); | ||
for ( const attr of lazyEmbedScript.attributes ) { | ||
if ( attr.nodeName === 'type' ) { | ||
// Omit type=application/vnd.embed-optimizer.javascript type. | ||
continue; | ||
} | ||
embedScript.setAttribute( | ||
attr.nodeName === 'data-original-type' | ||
? 'type' | ||
: attr.nodeName, | ||
attr.nodeValue | ||
); | ||
} | ||
lazyEmbedScript.replaceWith( embedScript ); | ||
lazyEmbedObserver.unobserve( lazyEmbedParent ); | ||
} | ||
} | ||
}, | ||
{ | ||
rootMargin: '100% 0% 100% 0%', | ||
threshold: 0, | ||
} | ||
); | ||
|
||
for ( const lazyEmbedScript of lazyEmbedsScripts ) { | ||
const lazyEmbedParent = | ||
/** @type {HTMLElement} */ lazyEmbedScript.parentNode; | ||
if ( lazyEmbedParent instanceof HTMLElement ) { | ||
lazyEmbedScriptsByParents.set( lazyEmbedParent, lazyEmbedScript ); | ||
lazyEmbedObserver.observe( lazyEmbedParent ); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters