Search code examples
laravellaravel-8lazy-loadinglaravel-livewireturbolinks

Laravel Livewire Turbolinks with Image lazyload


I am trying to build a website on Laravel Livewire with Vanilla Lazyload and Turbolink. On refreshing the page, image on page is lazyloaded, but soon I click on link, image do not lazy load until I manually refresh or enter the page. Default low quality images is visible which are just placeholder.

Anyone could guide or share a link so I can lazyload images in Livewire Turbolink. ANy other suggestion to make application act like a SPA, also welcomes.

Thanks.


Edit


//app.js
const Turbolink = require('turbolinks');
Turbolink.start();
window.LazyLoad = require('vanilla-lazyload');
// card.blade.php
<a href="{{ $url }}" class="hover:text-black">
    <div class="grid grid-cols-3 gap-2 bg-white rounded-lg hover:shadow-md border border-slate-100 py-4 hover:bg-slate-100 ease-in duration-300 cursor-pointer px-2">
        <img src="{{ asset('img/defaults/banner.jpg') }}" data-src="{{ $image }}" class="lazy w-52 mx-auto my-2">
        <div class="col-span-2">
            <p class="text-sm pt-3 font-inter m-auto">16 Jul, 2022</p>
            <h3 class="text-xl font-frank m-auto">{{ $title }}</h3>
        </div>
    </div>
</a>

When I refresh the page via F5 or manually enter address, this is how images are loaded which is what I want.

on page refresh how I images are loaded

This is how I end up on clicking any link which is processed by Turbolink.

on clicking any link on page which is processed by Turbolink I end up with low quality images only. like this


Solution

  • Ok, got the answer after a lot of research.

    in turbolinks, on clicking any URL you need to re-init your js on load, which can be done in JS as

    window.addEventListener('turbolinks:load', function(){...}
    

    via jQuery

    $(document).on('turbolinks:visit',function(){...}
    

    This might be useful for someone, who visits this post. You actually need to listen to event and then re-init.

    This is useful if you are using Turbolink 5 or newer version. For older version you need to listen for page:load instead of turbolinks:visit.