Lazy loading sliders and Google PageSpeed render blocking issue

Love them or hate them, sliders appear on many websites. Many clients ask for them so we use them a lot on the WordPress sites we build. Using the Advanced Custom Fields Repeater field, we can make the banners editable for clients too. All good, aside from the file size of using multiple large images. To counter this we started using lazy loading code that loads the slider using a dummy image and then loads the actual slider images from a data attribute.

Loading smaller images for mobile users

Using multiple massive images on mobile didn’t make sense, so we also tweaked the code to load smaller images for mobile sizes. jRespond was used for this and allows jQuery code to be run at various breakpoints. This meant uploading more images but the speed gains were impressive. There was one problem though – the jQuery slider was causing a ‘render blocking’ error on Google Pagespeed and limiting the scores we could achieve. Getting green ticks for desktop and mobile is ideal, so I needed a better option for this.

Vanilla Javascript to the rescue

The solution was to use vanilla Javascript and always load the mobile banner image. The mobile banner is a smaller file and doesn’t impact the desktop load time too much as desktop users are likely to be using a faster connection. By not using any jQuery, the jQuery library isn’t loaded. By loading the mobile image and not switching the data src, there is no delay on mobiles. Desktops load the larger images in  quickly.

Is Vanilla Javascript the way forward for WordPress?

The recent WooCommerce v3 update uses PhotoSwipe for the product gallery and this isn’t based on jQuery. While jQuery can be easier to work with, loading the jQuery library isn’t always necessary when vanilla Javascript can handle things on its own. I’m interested to see whether WordPress core and the plugins WordPress own like WooCommerce continue to use jQuery or whether they increase the vanilla Javascript used.