Skip to content

A platform for community discussion. Free, open, simple.

PERF: Lazy load full app embed iframe with IntersectionObserver (#39299)

Rafael dos Santos Silva0e6da77ff0ff
diff --git a/frontend/discourse/admin/controllers/admin-embedding/index.js b/frontend/discourse/admin/controllers/admin-embedding/index.js
index 534aeee9c6a..13bb0d11894 100644
--- a/frontend/discourse/admin/controllers/admin-embedding/index.js
+++ b/frontend/discourse/admin/controllers/admin-embedding/index.js
@@ -26,7 +26,9 @@ export default class AdminEmbeddingIndexController extends Controller {
const fullAppLines = this.fullAppMode
? `
fullApp: true,
- embedHeight: '800px',`
+ embedHeight: '800px',
+ // lazyLoad: false, // disable lazy loading of the iframe
+ // lazyLoadMargin: '1000', // pixels before viewport to start loading`
: "";
const html = `<div id='discourse-comments'></div>
diff --git a/public/javascripts/embed.js b/public/javascripts/embed.js
index a541ce1699c..e14e0b5ddfa 100644
--- a/public/javascripts/embed.js
+++ b/public/javascripts/embed.js
@@ -57,7 +57,6 @@
}
}
- iframe.src = src;
iframe.id = "discourse-embed-frame";
iframe.width = "100%";
iframe.frameBorder = "0";
@@ -67,7 +66,29 @@
}
iframe.referrerPolicy =
DE.discourseReferrerPolicy || "no-referrer-when-downgrade";
- comments.appendChild(iframe);
+
+ var lazyLoad = DE.fullApp && DE.lazyLoad !== false;
+
+ if (lazyLoad && "IntersectionObserver" in window) {
+ var margin = parseInt(DE.lazyLoadMargin, 10);
+ if (isNaN(margin)) {
+ margin = 1000;
+ }
+ comments.appendChild(iframe);
+ var observer = new IntersectionObserver(
+ function (entries) {
+ if (entries[0].isIntersecting) {
+ iframe.src = src;
+ observer.disconnect();
+ }
+ },
+ { rootMargin: margin + "px" }
+ );
+ observer.observe(iframe);
+ } else {
+ iframe.src = src;
+ comments.appendChild(iframe);
+ }
// Thanks http://amendsoft-javascript.blogspot.ca/2010/04/find-x-and-y-coordinate-of-html-control.html
function findPosY(obj) {