Last Updated: January 10, 2017
·
2.179K
· kim3er

Responsive carouFredSel stacks on page load

I'm quite proud of this one, but I'd be interested to know if there's a better way.

An issue that occurs with a lot of the responsive carousel plugins that I've used recently, is stacking of content on page load. The content appears briefly before the plugin (in this specific case, carouFredSel) works out the ideal height the container based on the slide's current height.

This occurs because the plugin requires the height of the first slide, so that it can adjust the container's height appropriately.

My solution, for situations where the slide content is frame by an image, is to wait for the first of the images to load before initialising the slider.

<div class="target-carousel" style="height: 0; overflow: hidden;">
    // Carousel here
</div>
var sliderLoaded = false;
function loadSlider() {
    if (sliderLoaded === true) {
        return false;
    }

    sliderLoaded = true;

    // Load slider here
};

$(window)
    .on('load', function() {
        var img = new Image();

        img.onload = loadSliders;

        img.src = $('.target-carousel li img').first().attr('src');

        setTimeout(loadSliders, 2000);
    });

I provide a two second fallback for edge cases on older browsers where the onload event doesn't fire.

The example uses window's load event because this is carouFredSel's preference.