Skip to main content

Cara Defer Offscreen Image/Gambar Postingan di Blogger

Peringatan defer offscreen image muncul belum lama ini pada google pagespeed versi terbaru. Ketika kita mengecek url postingan blog di google pagespeed maka akan tampak saran untuk mendefer gambar postingan. Hal itu terjadi karena gambar memang dapat memperbesar waktu loading suatu halaman. Anda dapat melihatnya seperti pada thumbnail artikel ini. Setelah menerapkan metode ini saran tersebut hilang.

Pada awalnya saran ini saya abaikan, namun lama kelamaan saya pensaran juga. Saya berpikir akan lebih baik jika kita bisa mendefer gambar ini. Terlebih jika blog yang dikelola adalah berupa blog tutorial yang harus menyediakan banyak gambar.

Ada beberapa cara yang bisa digunakan untuk mendefer gambar. Misalnya seperti progressive image loader yang digunakan oleh web medium. Namun sudah saya coba untuk menerapkan metode ini di blogger tidak ada cara yang otomatis. Artinya kita harus menambahkan manual pada gambar yang ingin di publish. Sedangkan gambar yang sudah dipublish belum saya dapatkan caranya untuk blogger.
cara mengatasi defer offsreen image

Kemudian akhirnya saya mendapatkan metode defer image pada blog kompiajaib dengan menggunakan lazyload. Cara ini lumayan ampuh untuk mengatasi masalah ini dan bisa diaplikasikan untuk gambar yang sudah di publish.

Silahkan copy dan paste script berikut sebelum tag </body>.

<script>
//<![CDATA[
/*! lazysizes - v4.1.5 */
!function(a,b){var c=b(a,a.document);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}(window,function(a,b){"use strict";if(b.getElementsByClassName){var c,d,e=b.documentElement,f=a.Date,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h],k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&&p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&&a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&&u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,d,e,f,g){var h=b.createEvent("Event");return e||(e={}),e.instance=c,h.initEvent(d,!f,!g),h.detail=e,a.dispatchEvent(h),h},w=function(b,c){var e;!g&&(e=a.picturefill||d.pf)?(c&&c.src&&!b[i]("srcset")&&b.setAttribute("srcset",c.src),e({reevaluate:!0,elements:[b]})):c&&c.src&&(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c<d.minSize&&b&&!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&&!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,c=0,e=d.throttleDelay,g=d.ricTimeout,h=function(){b=!1,c=f.now(),a()},i=m&&g>49?function(){m(h,{timeout:g}),g!==d.ricTimeout&&(g=d.ricTimeout)}:A(function(){k(h)},!0);return function(a){var d;(a=!0===a)&&(g=33),b||(b=!0,d=e-(f.now()-c),d<0&&(d=0),a||d<9?i():k(i,d))}},C=function(a){var b,c,d=99,e=function(){b=null,a()},g=function(){var a=f.now()-c;a<d?k(g,d-a):(m||e)(e)};return function(){c=f.now(),b||(b=k(g,d))}};!function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};d=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in d||(d[b]=c[b]);a.lazySizesConfig=d,k(function(){d.init&&F()})}();var D=function(){var g,l,m,o,p,y,D,F,G,H,I,J=/^img$/i,K=/^iframe$/i,L="onscroll"in a&&!/(gle|ing)bot/.test(navigator.userAgent),M=0,N=0,O=0,P=-1,Q=function(a){O--,a&&a.target&&u(a.target,Q),(!a||O<0||!a.target)&&(O=0)},R=function(a,c){var d,f=a,g="hidden"==x(b.body,"visibility")||"hidden"!=x(a.parentNode,"visibility")&&"hidden"!=x(a,"visibility");for(F-=c,I+=c,G-=c,H+=c;g&&(f=f.offsetParent)&&f!=b.body&&f!=e;)(g=(x(f,"opacity")||1)>0)&&"visible"!=x(f,"overflow")&&(d=f.getBoundingClientRect(),g=H>d.left&&G<d.right&&I>d.top-1&&F<d.bottom+1);return g},S=function(){var a,f,h,j,k,m,n,p,q,r,s,t,u=c.elements;if((o=d.loadMode)&&O<8&&(a=u.length)){for(f=0,P++,r=!d.expand||d.expand<1?e.clientHeight>500&&e.clientWidth>500?500:370:d.expand,s=r*d.expFactor,t=d.hFac,N<s&&O<1&&P>2&&o>2&&!b.hidden?(N=s,P=0):N=o>1&&P>1&&O<6?r:M;f<a;f++)if(u[f]&&!u[f]._lazyRace)if(L)if((p=u[f][i]("data-expand"))&&(m=1*p)||(m=N),q!==m&&(y=innerWidth+m*t,D=innerHeight+m,n=-1*m,q=m),h=u[f].getBoundingClientRect(),(I=h.bottom)>=n&&(F=h.top)<=D&&(H=h.right)>=n*t&&(G=h.left)<=y&&(I||H||G||F)&&(d.loadHidden||"hidden"!=x(u[f],"visibility"))&&(l&&O<3&&!p&&(o<3||P<4)||R(u[f],m))){if($(u[f]),k=!0,O>9)break}else!k&&l&&!j&&O<4&&P<4&&o>2&&(g[0]||d.preloadAfterLoad)&&(g[0]||!p&&(I||H||G||F||"auto"!=u[f][i](d.sizesAttr)))&&(j=g[0]||u[f]);else $(u[f]);j&&!k&&$(j)}},T=B(S),U=function(a){s(a.target,d.loadedClass),t(a.target,d.loadingClass),u(a.target,W),v(a.target,"lazyloaded")},V=A(U),W=function(a){V({target:a.target})},X=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},Y=function(a){var b,c=a[i](d.srcsetAttr);(b=d.customMedia[a[i]("data-media")||a[i]("media")])&&a.setAttribute("media",b),c&&a.setAttribute("srcset",c)},Z=A(function(a,b,c,e,f){var g,h,j,l,o,p;(o=v(a,"lazybeforeunveil",b)).defaultPrevented||(e&&(c?s(a,d.autosizesClass):a.setAttribute("sizes",e)),h=a[i](d.srcsetAttr),g=a[i](d.srcAttr),f&&(j=a.parentNode,l=j&&n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&&(h||g||l),o={target:a},p&&(u(a,Q,!0),clearTimeout(m),m=k(Q,2500),s(a,d.loadingClass),u(a,W,!0)),l&&q.call(j.getElementsByTagName("source"),Y),h?a.setAttribute("srcset",h):g&&!l&&(K.test(a.nodeName)?X(a,g):a.src=g),f&&(h||l)&&w(a,{src:g})),a._lazyRace&&delete a._lazyRace,t(a,d.lazyClass),z(function(){(!p||a.complete&&a.naturalWidth>1)&&(p?Q(o):O--,U(o))},!0)}),$=function(a){var b,c=J.test(a.nodeName),e=c&&(a[i](d.sizesAttr)||a[i]("sizes")),f="auto"==e;(!f&&l||!c||!a[i]("src")&&!a.srcset||a.complete||r(a,d.errorClass)||!r(a,d.lazyClass))&&(b=v(a,"lazyunveilread").detail,f&&E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,O++,Z(a,b,f,e,c))},_=function(){if(!l){if(f.now()-p<999)return void k(_,999);var a=C(function(){d.loadMode=3,T()});l=!0,d.loadMode=3,T(),j("scroll",function(){3==d.loadMode&&(d.loadMode=2),a()},!0)}};return{_:function(){p=f.now(),c.elements=b.getElementsByClassName(d.lazyClass),g=b.getElementsByClassName(d.lazyClass+" "+d.preloadClass),j("scroll",T,!0),j("resize",T,!0),a.MutationObserver?new MutationObserver(T).observe(e,{childList:!0,subtree:!0,attributes:!0}):(e[h]("DOMNodeInserted",T,!0),e[h]("DOMAttrModified",T,!0),setInterval(T,999)),j("hashchange",T,!0),["focus","mouseover","click","load","transitionend","animationend","webkitAnimationEnd"].forEach(function(a){b[h](a,T,!0)}),/d$|^c/.test(b.readyState)?_():(j("load",_),b[h]("DOMContentLoaded",T),k(_,2e4)),c.elements.length?(S(),z._lsFlush()):T()},checkElems:T,unveil:$}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;f<g;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),e=function(a,b,d){var e,f=a.parentNode;f&&(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width)&&d!==a._lazysizesWidth&&c(a,f,e,d))},f=function(){var b,c=a.length;if(c)for(b=0;b<c;b++)e(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(d.autosizesClass),j("resize",g)},checkElems:g,updateElem:e}}(),F=function(){F.i||(F.i=!0,E._(),D._())};return c={cfg:d,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}}}); 

for(var imgEl=document.getElementsByTagName("img"),i=0;i<imgEl.length;i++)imgEl[i].getAttribute("src")&&(imgEl[i].setAttribute("data-src",imgEl[i].getAttribute("src")),imgEl[i].className+=" lazyload",imgEl[i].setAttribute("src","data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="));$(document).ready(function(){$('iframe[src*="youtube.com"]').wrap('<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;margin:0 auto;width:100%"></div>').css({position:"absolute",top:"0",left:"0",width:"100%",height:"100%",border:"0"}).addClass("lazyload").each(function(){$(this).attr("data-src",$(this).attr("src")),$(this).removeAttr("src","")})});
//]]>
</script>

Script di atas sudah saya uraikan semua, namun jika Anda ingin menghosting scriptnya menjadi external. Silahkan copy script yang saya tandai dengan warna merah.

Namun jika tidak ingin menghostingnya, silahkan langsung copy keseluruhan script di atas sebelum tag </body>.

Cara ini selain digunakan untuk defer gambar bisa juga untuk mendefer iframe video yang diembed di postingan.

Kemudian cek lagi url postingan pada google pagespeed antara sebelum menggunakan cara ini dan sesudahnya.
Comment Policy: Silahkan tuliskan komentar Anda yang sesuai dengan topik postingan halaman ini. Komentar yang berisi tautan tidak akan ditampilkan sebelum disetujui.
Buka Komentar
Tutup Komentar