(()=>{var t={546:function(t){t.exports=function(){"use strict";function t(t){for(var e=1;et+"x"+e)).join(","),i=`[${t.type}|${t.tagId}|${n}] `;this.log(i+e)}trackStat(t){window._stq=window._stq||[],window._stq.push(["extra",{x_wordads_smart:t}])}recordTracksEvent(t,e){e=e||{},window._tkq=window._tkq||[],window._tkq.push(["recordEvent",t,e])}injectStyles(t){let e=document.createElement("style");return e.type="text/css",e.innerText=t,document.head.appendChild(e),e}createAdSnippet(t){let e=document.createElement("div"),n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");return e.classList.add("wordads-ad"),n.classList.add("wordads-ad-title"),i.classList.add("wordads-ad-content"),o.classList.add("wordads-ad-controls"),n.innerText=this.config._.title,i.id=t,o.innerHTML=this.tcData?`${this.config._.privacy_settings}`:"",e.appendChild(n),e.appendChild(i),e.appendChild(o),e}wrapSnippet(t){let e=document.createElement("div");return e.classList.add("wordads-ad-wrapper"),e.appendChild(t),e}insertInlineAdBefore(t){let e=this.getRandomTagId(),n=this.createAdSnippet(e),i=this.wrapSnippet(n);t.insertAdjacentElement("beforebegin",i),this.slots.push({tagId:e,formatId:this.config.inline.format_id,type:a,sizes:[[300,250]],element:i,isLazy:!0})}call(t){this.config.inline.adflow_enabled?this.callAdFlow(t):this.callSmart(t)}callSmart(t){let e=this;window.sas.cmd.push((function(){e.logSlot(t,"calling Smart"),window.sas.call("std",{siteId:e.config.site_id,pageId:e.config.page_id,formatId:t.formatId,tagId:t.tagId,content_source_id:e.config.blog_id,target:e.config.target})}))}callAdFlow(t){this.logSlot(t,"calling AdFlow");let e=new XMLHttpRequest,n=this;e.onreadystatechange=function(){if(XMLHttpRequest.DONE===e.readyState){if(performance.mark(`${t.tagId}-end`),200!==e.status)return void window.sas.events.fire("noad",{tagId:t.tagId,formatId:t.formatId},t.tagId);let i=JSON.parse(e.response)[t.tagId],o=!i.hasOwnProperty("ScriptNoAd");if(o){let t=document.createElement("script");t.type=i.ContentType,t.innerHTML=i.Content,document.body.appendChild(t)}else{let e=new XMLHttpRequest;e.open("GET",i.ScriptNoAd),e.send(),window.sas.events.fire("noad",{tagId:t.tagId,formatId:t.formatId},t.tagId)}n.trackAdFlowRequestLatency(o,t.tagId)}};let i={timestamp:Date.now(),networkId:this.config.network_id,siteId:this.config.site_id,pageId:this.config.page_id,content_source_id:this.config.blog_id,wp_post_id:this.config.post_id,getAdContent:!0,ads:[{formatId:t.formatId,tagId:t.tagId,target:this.config.target,isLazy:!1}],gdpr:!1,pageUrl:window.location.href,uid:this.getOrCreateUID()};this.usPrivacy&&(i.us_privacy=this.usPrivacy),this.tcData&&(i.gdpr=!0,i.gdpr_consent=this.tcData.tcString),e.open("POST","https://af.pubmine.com"),e.setRequestHeader("Content-type","application/json"),performance.mark(`${t.tagId}-start`),e.send(JSON.stringify(i))}trackAdFlowRequestLatency(t,e){let n=performance.measure(`${e}-duration`,`${e}-start`,`${e}-end`),i={has_ad:t,request_time:Math.round(n.duration),theme:this.config.theme};navigator.connection&&(i.connection_effective_type=navigator.connection.effectiveType,i.connection_downlink=navigator.connection.downlink),this.recordTracksEvent("wpcom_wordads_adflow",i)}getOrCreateUID(){if(null!==this.uid)return this.uid;if(!this.hasUserConsent())return this.uid="",this.uid;const t="wordads_uid",e=o.default.get(t);if(e)return this.log(`Reused UID value ${e}`),this.uid=e,this.uid;const n=this.getCookiesSharedDomain(t,window.location.hostname);return window.localStorage&&!n||(this.uid=this.createUIDFromCookies(t,30,n)),this.uid=this.uid||this.getOrCreateUIDFromLocalStorage(t,30),this.log(`UID value: ${this.uid}`),this.uid}hasUserConsent(){return!this.tcData||!0===this.tcData.vendor.consents[496]&&!0===this.tcData.purpose.consents[1]}getCookiesSharedDomain(t,e){const n=e.split(".");if(n.length<=2)return null;let i=null,a=0;for(const s of n){if(a+=s.length,i=e.substring(a),a>=e.length)return null;const n=o.default.withAttributes({domain:i});if(n.set(t,"1")&&n.get(t))return n.remove(t),i;a++}return null}createUIDFromCookies(t,e,n){const i={expires:e,domain:n||window.location.hostname};this.log(`Created UID from Cookies on ${i.domain}`);const a=o.default.withAttributes(i),s=this.generateUIDValue();return a.set(t,s),s}getOrCreateUIDFromLocalStorage(t,e){this.log("UID from localStorage");const n=(localStorage.getItem(t)||"").split(":");let i=n[0];const o=(new Date).getTime();let a=parseInt(n[1]);return(!i||o>a)&&(i=this.generateUIDValue(),a=o+24*e*60*60*1e3,localStorage.setItem(t,i+":"+a)),i}generateUIDValue(){return Math.random().toString(36).substring(2,10)+(new Date).getTime().toString()}insertFallbackAd(t,e){let n=(window.sas_fallback||[]).filter((function(t){return t.type===e}));if(0===n.length)return t.remove(),void this.log(`No fallback found for ${e}, snippet removed`);let i=n[0].tag.replaceAll("{{unique_id}}",Math.trunc(1e6*Math.random())),o=document.createElement("div");o.innerHTML=i,i=o.childNodes[0].nodeValue;let a=document.createElement("div");a.innerHTML=i,t.style.position="relative",t.style.visibility="visible",t.innerHTML=a.innerHTML,a.querySelectorAll("script").forEach((function(t){t.parentNode&&t.parentNode.removeChild(t);let e=document.createElement("script");t.src?e.src=t.src:t.textContent?e.textContent=t.textContent:t.innerText&&(e.innerText=t.innerText),document.body.appendChild(e)})),this.trackStat("fallback_"+e)}getChildrenByTag(t,e){let n=[];for(let i=0;i{let e=this.getElementGlobalPosition(t);n.bottome.bottom||n.righte.left||(i=!0)})),i}initInlineAds(){if(!this.config.inline.enabled)return;this.log(`Initializing ${a}`);let t=document.getElementById("wordads-inline-marker");if(!t)return void this.trackStat("inline_no_marker");let e=t.parentElement;if(!e)return;this.injectStyles(".wordads-ad-wrapper{position:absolute;visibility:hidden;font:11px Arial,sans-serif;letter-spacing:1px;text-decoration:none;width:100%;margin:25px auto;padding:0;clear:both}.wordads-ad-title{margin:0 auto 5px}.wordads-ad-controls{margin:5px auto 0;text-align:right}.wordads-ad-controls span{cursor:pointer}.wordads-ad{width:300px;max-width:580px;margin:0 auto}.wordads-ad iframe{margin:0;padding:0}.wordads-ad.wordads-ad-responsive{width:100%}"),t.remove();let n=this.config.inline.max_slots,i=this.config.inline.max_blaze_slots,o=0,s=window.innerHeight,r=Math.ceil(1.35*s),d=Math.ceil(2.5*s),l=e.getBoundingClientRect().top+window.scrollY+r,c=this.getChildrenByTag(e,"p"),g=this.getFloatingElements(e);c.forEach((t=>{let e=t.getBoundingClientRect().top+window.scrollY,s=t.previousElementSibling;if(e>l&&oo)this.insertInlineAdBefore(t),this.trackStat("render_inline");else{let e=document.createElement("div");e.className="wordads-ad-wrapper",t.insertAdjacentElement("beforebegin",e),this.insertFallbackAd(e,a),this.trackStat("render_inline_fallback")}l=e+d,o++}})),0===o&&this.trackStat("inline_no_insert")}handleNoAd(t){let e=this.getSlotByTagId(t.tagId);e?(this.logSlot(e,"got NoAd"),this.logSlot(e,"requesting fallback"),this.insertFallbackAd(e.element,e.type),this.trackStat("noad_"+e.type)):this.log(`NoAd: no slot found for tag id: ${t.tagId}, format id: ${t.formatId}`)}handleAd(t){let e=this.getSlotByTagId(t.tagId);e?(this.logSlot(e,"got Ad"),e.element.style.position="relative",e.element.style.visibility="visible",e.onAd&&e.onAd(),this.trackStat("ad_"+e.type)):this.log(`Ad: no slot found for tag id: ${t.tagId}, format id: ${t.formatId}`)}handlePostMessage(t){if("object"!=typeof t.data)return;if("wa-inline-frame"!==t.data.type)return;let e=document.getElementsByTagName("iframe");for(let n=0;n{e.style.maxWidth=t.data.maxWidth})));break}}getSlotByTagId(t){return this.slots.find((e=>e.tagId===t))}getRandomTagId(){return"wordads-ad-"+Math.trunc(1e6*Math.random())}initConsent(){this.log("Initializing consent...");let t=this;window.__uspapi?(this.log("Querying USP API..."),window.__uspapi("getUSPData",1,(function(e,n){n&&e.uspString&&(t.usPrivacy=e.uspString,t.log("USP API data found. Setting consent: "+t.usPrivacy))}))):this.log("USP API not found"),window.__tcfapi?(this.log("Querying TCF API..."),window.__tcfapi("addEventListener",2,(function(e,n){n&&e.gdprApplies?(t.tcData=e,t.log("TCF API data found. Setting consent: "+t.tcData.tcString)):t.log("TCF API data found. GDPR does not apply")}))):this.log("TCF API not found")}initSmart(){this.log("Initializing Smart");let t=this;window.sas.cmd.push((function(){window.sas.setup({networkid:t.config.network_id,domain:"https://www15.smartadserver.com",async:!0})})),window.sas.cmd.push((function(){window.sas.events.on("noad",(e=>{t.handleNoAd(e)}))})),window.sas.cmd.push((function(){window.sas.events.on("ad",(e=>{t.handleAd(e)}))}))}throttle(t,e){let n=!1;return(...i)=>{n||(t(...i),n=!0,setTimeout((()=>{n=!1}),e))}}isElementInLazyViewport(t){let e=window.innerHeight,n=window.scrollY,i=n-e,o=n+2*e,a=this.getElementGlobalPosition(t);return!(a.bottom<=i||a.top>=o)}processAds(){0!==this.slots.length&&this.slots.forEach((t=>{t.isLoaded||(!t.isLazy||this.isElementInLazyViewport(t.element))&&(this.logSlot(t,"in view"),t.isLoaded=!0,this.call(t))}))}preInit(){this.log("Running Pre Init");let t=this;if(void 0===window.sas){this.log("Fetching Smart script"),window.sas={cmd:[]};let e=document.createElement("script");e.src="https://ced.sascdn.com/tag/3905/smart.js",e.addEventListener("load",(function(){t.log("Smart JS loaded"),"loading"!==document.readyState?t.init():document.addEventListener("DOMContentLoaded",(()=>{t.init()}))})),document.head.appendChild(e)}}init(){this.log("Init..."),this.mergeConfig(),this.initConsent(),this.initSmart(),this.initAds()}initAds(){this.initialized||(this.initialized=!0,this.initInlineAds(),this.processAds())}deepMerge(t,e){for(let n in e)e.hasOwnProperty(n)&&(e[n]instanceof Object&&t[n]instanceof Object?t[n]=this.deepMerge(t[n],e[n]):t[n]=e[n]);return t}mergeConfig(){let t={},e=document.getElementById("adflow-configuration");e&&(t=JSON.parse(e.innerText)),this.config=this.deepMerge(t,window.wa_smart),this.log("Merged config:"),this.log(this.config)}};s.preInit(),document.addEventListener("scroll",s.throttle((()=>{s.processAds()}),250)),document.addEventListener("resize",s.throttle((()=>{s.processAds()}),250)),window.addEventListener("message",(t=>{s.handlePostMessage(t)}))}},e={};!function n(i){var o=e[i];if(void 0!==o)return o.exports;var a=e[i]={exports:{}};return t[i].call(a.exports,a,a.exports,n),a.exports}(428)})();; /* global wpcom_reblog */ var jetpackLikesWidgetBatch = []; var jetpackLikesMasterReady = false; // Due to performance problems on pages with a large number of widget iframes that need to be loaded, // we are limiting the processing at any instant to unloaded widgets that are currently in viewport, // plus this constant that will allow processing of widgets above and bellow the current fold. // This aim of it is to improve the UX and hide the transition from unloaded to loaded state from users. var jetpackLikesLookAhead = 2000; // pixels // Keeps track of loaded comment likes widget so we can unload them when they are scrolled out of view. var jetpackCommentLikesLoadedWidgets = []; var jetpackLikesDocReadyPromise = new Promise( resolve => { if ( document.readyState !== 'loading' ) { resolve(); } else { window.addEventListener( 'DOMContentLoaded', () => resolve() ); } } ); function JetpackLikesPostMessage( message, target ) { if ( typeof message === 'string' ) { try { message = JSON.parse( message ); } catch ( e ) { return; } } if ( target && typeof target.postMessage === 'function' ) { try { target.postMessage( JSON.stringify( { type: 'likesMessage', data: message, } ), '*' ); } catch ( e ) { return; } } } function JetpackLikesBatchHandler() { const requests = []; document.querySelectorAll( 'div.jetpack-likes-widget-unloaded' ).forEach( widget => { if ( jetpackLikesWidgetBatch.indexOf( widget.id ) > -1 ) { return; } if ( ! jetpackIsScrolledIntoView( widget ) ) { return; } jetpackLikesWidgetBatch.push( widget.id ); var regex = /like-(post|comment)-wrapper-(\d+)-(\d+)-(\w+)/, match = regex.exec( widget.id ), info; if ( ! match || match.length !== 5 ) { return; } info = { blog_id: match[ 2 ], width: widget.width, }; if ( 'post' === match[ 1 ] ) { info.post_id = match[ 3 ]; } else if ( 'comment' === match[ 1 ] ) { info.comment_id = match[ 3 ]; } info.obj_id = match[ 4 ]; requests.push( info ); } ); if ( requests.length > 0 ) { JetpackLikesPostMessage( { event: 'initialBatch', requests: requests }, window.frames[ 'likes-master' ] ); } } function JetpackLikesMessageListener( event ) { let message = event && event.data; if ( typeof message === 'string' ) { try { message = JSON.parse( message ); } catch ( err ) { return; } } const type = message && message.type; const data = message && message.data; if ( type !== 'likesMessage' || typeof data.event === 'undefined' ) { return; } // We only allow messages from one origin const allowedOrigin = 'https://widgets.wp.com'; if ( allowedOrigin !== event.origin ) { return; } switch ( data.event ) { case 'masterReady': jetpackLikesDocReadyPromise.then( () => { jetpackLikesMasterReady = true; const stylesData = { event: 'injectStyles', }; const sdTextColor = document.querySelector( '.sd-text-color' ); const sdLinkColor = document.querySelector( '.sd-link-color' ); const sdTextColorStyles = ( sdTextColor && getComputedStyle( sdTextColor ) ) || {}; const sdLinkColorStyles = ( sdLinkColor && getComputedStyle( sdLinkColor ) ) || {}; // enable reblogs if they are enabled for the page if ( document.body.classList.contains( 'jetpack-reblog-enabled' ) ) { JetpackLikesPostMessage( { event: 'reblogsEnabled' }, window.frames[ 'likes-master' ] ); } stylesData.textStyles = { color: sdTextColorStyles[ 'color' ], fontFamily: sdTextColorStyles[ 'font-family' ], fontSize: sdTextColorStyles[ 'font-size' ], direction: sdTextColorStyles[ 'direction' ], fontWeight: sdTextColorStyles[ 'font-weight' ], fontStyle: sdTextColorStyles[ 'font-style' ], textDecoration: sdTextColorStyles[ 'text-decoration' ], }; stylesData.linkStyles = { color: sdLinkColorStyles[ 'color' ], fontFamily: sdLinkColorStyles[ 'font-family' ], fontSize: sdLinkColorStyles[ 'font-size' ], textDecoration: sdLinkColorStyles[ 'text-decoration' ], fontWeight: sdLinkColorStyles[ 'font-weight' ], fontStyle: sdLinkColorStyles[ 'font-style' ], }; JetpackLikesPostMessage( stylesData, window.frames[ 'likes-master' ] ); JetpackLikesBatchHandler(); } ); break; case 'showLikeWidget': { const placeholder = document.querySelector( `#${ data.id } .likes-widget-placeholder` ); if ( placeholder ) { placeholder.style.display = 'none'; } break; } case 'showCommentLikeWidget': { const placeholder = document.querySelector( `#${ data.id } .likes-widget-placeholder` ); if ( placeholder ) { placeholder.style.display = 'none'; } break; } case 'killCommentLikes': // If kill switch for comment likes is enabled remove all widgets wrappers and `Loading...` placeholders. document .querySelectorAll( '.jetpack-comment-likes-widget-wrapper' ) .forEach( wrapper => wrapper.remove() ); break; case 'clickReblogFlair': if ( wpcom_reblog && typeof wpcom_reblog.toggle_reblog_box_flair === 'function' ) { wpcom_reblog.toggle_reblog_box_flair( data.obj_id, data.post_id ); } break; case 'hideOtherGravatars': { hideLikersPopover(); break; } case 'showOtherGravatars': { const container = document.querySelector( '#likes-other-gravatars' ); if ( ! container ) { break; } const list = container.querySelector( 'ul' ); container.style.display = 'none'; list.innerHTML = ''; container .querySelectorAll( '.likes-text span' ) .forEach( item => ( item.textContent = data.totalLikesLabel ) ); ( data.likers || [] ).forEach( async ( liker, index ) => { if ( liker.profile_URL.substr( 0, 4 ) !== 'http' ) { // We only display gravatars with http or https schema return; } const element = document.createElement( 'li' ); list.append( element ); element.innerHTML = ` `; // Add some extra attributes through native methods, to ensure strings are sanitized. element.classList.add( liker.css_class ); element.querySelector( 'img' ).alt = data.avatarAltTitle.replace( '%s', liker.name ); element.querySelector( 'span' ).innerText = liker.name; if ( index === data.likers.length - 1 ) { element.addEventListener( 'keydown', ( e ) => { if ( e.key === 'Tab' && ! e.shiftKey ) { e.preventDefault(); hideLikersPopover(); JetpackLikesPostMessage( { event: 'focusLikesCount', parent: data.parent }, window.frames[ 'likes-master' ] ); } } ); } } ); const positionPopup = function() { const containerStyle = getComputedStyle(container); const isRtl = containerStyle.direction === 'rtl'; const el = document.querySelector( `*[name='${ data.parent }']` ); const rect = el.getBoundingClientRect(); const win = el.ownerDocument.defaultView; const offset = { top: rect.top + win.pageYOffset, left: rect.left + win.pageXOffset, }; // don't display yet or we get skewed window.innerWidth later container.style.display = 'none'; let containerLeft = 0; container.style.top = offset.top + data.position.top - 1 + 'px'; if ( isRtl ) { const visibleAvatarsCount = data && data.likers ? Math.min( data.likers.length, 5 ) : 0; // 24px is the width of the avatar + 4px is the padding between avatars containerLeft = offset.left + data.position.left + 24 * visibleAvatarsCount + 4; container.style.transform = 'translateX(-100%)'; } else { containerLeft = offset.left + data.position.left; } container.style.left = containerLeft + 'px'; // Container width - padding const initContainerWidth = data.width - 20; const rowLength = Math.floor( initContainerWidth / 37 ); // # of rows + (avatar + avatar padding) + text above + container padding let height = Math.ceil( data.likers.length / rowLength ) * 37 + 17 + 22; if ( height > 204 ) { height = 204; } // If the popup is overflows viewport width, we should show it on the next line // Push it offscreen to calculated rendered width const windowWidth = win.innerWidth; container.style.left = '-9999px'; container.style.display = 'block'; // If the popup exceeds the viewport width, // flip the position of the popup. const containerWidth = container.offsetWidth; const containerRight = containerLeft + containerWidth; if ( containerRight > windowWidth && ! isRtl) { containerLeft = rect.left + rect.width - containerWidth; } else if ( containerLeft - containerWidth < 0 && isRtl ) { container.style.transform = 'none'; containerLeft = rect.left; } // Set the container left container.style.left = containerLeft + 'px'; container.setAttribute( 'aria-hidden', 'false' ); } positionPopup(); container.focus(); const debounce = function( func, wait ) { var timeout; return function() { var context = this; var args = arguments; clearTimeout( timeout ); timeout = setTimeout( function() { func.apply( context, args ); }, wait ); }; }; const debouncedPositionPopup = debounce( positionPopup, 100 ); // Keep a reference of this function in the element itself // so that we can destroy it later container.__resizeHandler = debouncedPositionPopup; // When window is resized, resize the popup. window.addEventListener( "resize", debouncedPositionPopup ); } } } window.addEventListener( 'message', JetpackLikesMessageListener ); function hideLikersPopover() { const container = document.querySelector( '#likes-other-gravatars' ); if ( container ) { container.style.display = 'none'; container.setAttribute( 'aria-hidden', 'true' ); // Remove the resize event listener and cleanup. const resizeHandler = container.__resizeHandler; if ( resizeHandler ) { window.removeEventListener( "resize", resizeHandler ); delete container.__resizeHandler; } } } document.addEventListener( 'click', hideLikersPopover ); function JetpackLikesWidgetQueueHandler() { var wrapperID; if ( ! jetpackLikesMasterReady ) { setTimeout( JetpackLikesWidgetQueueHandler, 500 ); return; } // Restore widgets to initial unloaded state when they are scrolled out of view. jetpackUnloadScrolledOutWidgets(); var unloadedWidgetsInView = jetpackGetUnloadedWidgetsInView(); if ( unloadedWidgetsInView.length > 0 ) { // Grab any unloaded widgets for a batch request JetpackLikesBatchHandler(); } for ( var i = 0, length = unloadedWidgetsInView.length; i <= length - 1; i++ ) { wrapperID = unloadedWidgetsInView[ i ].id; if ( ! wrapperID ) { continue; } jetpackLoadLikeWidgetIframe( wrapperID ); } } function jetpackLoadLikeWidgetIframe( wrapperID ) { if ( typeof wrapperID === 'undefined' ) { return; } const wrapper = document.querySelector( '#' + wrapperID ); wrapper.querySelectorAll( 'iframe' ).forEach( iFrame => iFrame.remove() ); const placeholder = wrapper.querySelector( '.likes-widget-placeholder' ); // Post like iframe if ( placeholder && placeholder.classList.contains( 'post-likes-widget-placeholder' ) ) { const postLikesFrame = document.createElement( 'iframe' ); postLikesFrame.classList.add( 'post-likes-widget', 'jetpack-likes-widget' ); postLikesFrame.name = wrapper.dataset.name; postLikesFrame.src = wrapper.dataset.src; postLikesFrame.height = '55px'; postLikesFrame.width = '100%'; postLikesFrame.frameBorder = '0'; postLikesFrame.scrolling = 'no'; postLikesFrame.title = wrapper.dataset.title; placeholder.after( postLikesFrame ); } // Comment like iframe if ( placeholder.classList.contains( 'comment-likes-widget-placeholder' ) ) { const commentLikesFrame = document.createElement( 'iframe' ); commentLikesFrame.class = 'comment-likes-widget-frame jetpack-likes-widget-frame'; commentLikesFrame.name = wrapper.dataset.name; commentLikesFrame.src = wrapper.dataset.src; commentLikesFrame.height = '18px'; commentLikesFrame.width = '100%'; commentLikesFrame.frameBorder = '0'; commentLikesFrame.scrolling = 'no'; wrapper.querySelector( '.comment-like-feedback' ).after( commentLikesFrame ); jetpackCommentLikesLoadedWidgets.push( commentLikesFrame ); } wrapper.classList.remove( 'jetpack-likes-widget-unloaded' ); wrapper.classList.add( 'jetpack-likes-widget-loading' ); wrapper.querySelector( 'iframe' ).addEventListener( 'load', e => { JetpackLikesPostMessage( { event: 'loadLikeWidget', name: e.target.name, width: e.target.width }, window.frames[ 'likes-master' ] ); wrapper.classList.remove( 'jetpack-likes-widget-loading' ); wrapper.classList.add( 'jetpack-likes-widget-loaded' ); } ); } function jetpackGetUnloadedWidgetsInView() { const unloadedWidgets = document.querySelectorAll( 'div.jetpack-likes-widget-unloaded' ); return [ ...unloadedWidgets ].filter( item => jetpackIsScrolledIntoView( item ) ); } function jetpackIsScrolledIntoView( element ) { const top = element.getBoundingClientRect().top; const bottom = element.getBoundingClientRect().bottom; // Allow some slack above and bellow the fold with jetpackLikesLookAhead, // with the aim of hiding the transition from unloaded to loaded widget from users. return top + jetpackLikesLookAhead >= 0 && bottom <= window.innerHeight + jetpackLikesLookAhead; } function jetpackUnloadScrolledOutWidgets() { for ( let i = jetpackCommentLikesLoadedWidgets.length - 1; i >= 0; i-- ) { const currentWidgetIframe = jetpackCommentLikesLoadedWidgets[ i ]; if ( ! jetpackIsScrolledIntoView( currentWidgetIframe ) ) { const widgetWrapper = currentWidgetIframe && currentWidgetIframe.parentElement && currentWidgetIframe.parentElement.parentElement; // Restore parent class to 'unloaded' so this widget can be picked up by queue manager again if needed. widgetWrapper.classList.remove( 'jetpack-likes-widget-loaded' ); widgetWrapper.classList.remove( 'jetpack-likes-widget-loading' ); widgetWrapper.classList.add( 'jetpack-likes-widget-unloaded' ); // Bring back the loading placeholder into view. widgetWrapper .querySelectorAll( '.comment-likes-widget-placeholder' ) .forEach( item => ( item.style.display = 'block' ) ); // Remove it from the list of loaded widgets. jetpackCommentLikesLoadedWidgets.splice( i, 1 ); // Remove comment like widget iFrame. currentWidgetIframe.remove(); } } } var jetpackWidgetsDelayedExec = function ( after, fn ) { var timer; return function () { clearTimeout( timer ); timer = setTimeout( fn, after ); }; }; var jetpackOnScrollStopped = jetpackWidgetsDelayedExec( 250, JetpackLikesWidgetQueueHandler ); // Load initial batch of widgets, prior to any scrolling events. JetpackLikesWidgetQueueHandler(); // Add event listener to execute queue handler after scroll. window.addEventListener( 'scroll', jetpackOnScrollStopped, true ); ;