Skip to content

Commit 741f900

Browse files
committed
adding intersection observer for handled zones
1 parent 264a4ed commit 741f900

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

demo/story/index.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
// Listen for the loaded event
2525
window.addEventListener("zones-loaded", console.log("zones are loaded"));
2626

27+
// Listen for the intersection event
28+
window.addEventListener("zone", (e) => console.log("%s showing", e.detail.id));
29+
2730
// Demo-only show vips
2831
import { getValidInsertionPoints } from "/lib/zones.js";
2932
const vips = getValidInsertionPoints();

lib/zones.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// Internals
66
let map = new Map();
77
let fragment = new DocumentFragment();
8+
let observer = new IntersectionObserver(handleIntersection, { rootMargin: "500px" })
89

910
// Locker
1011
export let locker;
@@ -129,6 +130,9 @@ export class Zone {
129130
this.element.dataset.distributed = true;
130131
this.vip.insertAdjacentElement(loc, this.element);
131132
this.log(this.msg || "zone moved into new location");
133+
134+
// Observer for performance team
135+
observer.observe(this.element);
132136
}
133137
}
134138

@@ -450,3 +454,26 @@ export async function loadConfig(url) {
450454

451455
return config;
452456
}
457+
458+
/*
459+
* IntersectionObserver callback
460+
*/
461+
462+
function handleIntersection(entries, observer) {
463+
entries.forEach((entry) => {
464+
if(entry.isIntersecting) {
465+
// Build the event
466+
const loadZone = new CustomEvent("zone", {
467+
detail: {
468+
id: entry.target.id
469+
}
470+
});
471+
472+
// Send it
473+
window.dispatchEvent(loadZone);
474+
475+
// Only do it once
476+
observer.unobserve(entry.target);
477+
}
478+
});
479+
}

0 commit comments

Comments
 (0)