File app/Http/ViewComposers/LazyViewComposer.php
(link to Github)
use Illuminate\View\View;
class LazyViewComposer
{
public function compose(View $view)
{
$view->with('usesInternetExplorer', $this->usesInternetExplorer());
}
private function usesInternetExplorer(): bool
{
if (app()->runningInConsole()) {
return false;
}
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('~MSIE|Internet Explorer~i', $userAgent)) {
return true;
}
if (strpos($userAgent, 'Trident/7.0; rv:11.0') !== false) {
return true;
}
return false;
}
}
File app/Providers/ViewServiceProvider.php
(link to Github)
use App\Http\ViewComposers\LazyViewComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
public function register()
{
View::composer('front.components.lazy', LazyViewComposer::class);
}
}
File resources/views/front/components/lazy.blade.php
(link to Github)
@if($usesInternetExplorer)
{{ $slot }}
@else
<div data-lazy>
<template>
{{ $slot }}
</template>
</div>
@endif
Additional resources on view composers:
-
Povilas Korop | www.youtube.com
Published on