Loading, please wait...

picture of me
Joe Rushton Fullstack Web Developer

Lazy Loading iFrames in a Slick Slider Gallery

12th March 2017 Reading Time: 2 mins
Tags: Javascript

Why would you want to do this I hear ye ask? Essentially I had this niche problem at work today where a whole bunch of iFrames in the form of embedded 3D photos, were being loaded simultaneously in a gallery which caused the webpage to crash on not-so-powerful devices (Namely the office iPad that I was testing on).

For those of you that don't know about it, slick slider is an amazing javascript plugin by ken wheeler (http://kenwheeler.github.io/slick/) and if you're looking to standardize your web galleries, I definitely recommend it as your go-to.

The gallery already had a useful feature built in where it would delay the initial load of the iframe until the gallery is initialized.In practice that looks like

// iframes within the .iframe-gallery aren't loaded until .some-button is clicked
$('.some-button').on('click', function() {
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 3

But unfortunately it was loading all of them at the same time, causing my webpage to crash. A simple solution was to create a bit of code which switches out all of the iframes src attributes to a data-src (or any data prefixed attribute of your naming) until only the current iframe is visible.

var iframes = $('.iframe-gallery iframe');

// on page load switch out all of the srcs to data-src
iframes.each(function(index, value) {
 var src = $(this).attr('src');

 // set the data-src and wipe the src
 $(this).data('src', src);
 $(this).attr('src', '');

// on gallery init.. (slick slider callback function)
$('.iframe-gallery').on('init', function(){ 

  // load the first iframe since we are initializing
  iframes.eq(0).attr('src', iframes.eq(0).data('src'));

// on gallery change.. (slick slider callback function)
$('.iframe-gallery').on('beforeChange', function(event, slick, currentSlide, nextSlide){
  // emptying out the src attribute of the iframe with the index of the current slide
  iframes.eq(currentSlide).attr('src', '');

  // "loading" the next slides iframe
  iframes.eq(nextSlide).attr('src', iframes.eq(nextSlide).data('src'));
Back to Homepage

Find me on social media