chrgriffin/laravel-defer

在Laravel中自动延迟加载图片,直到页面加载完成后。

v1.0.2 2018-10-23 13:36 UTC

This package is auto-updated.

Last update: 2024-09-24 05:30:45 UTC


README

laravel-defer是一个包,它将自动将Blade模板中的普通图片标签延迟加载。你只需要开启它并嵌入脚本!

安装

你可以通过composer安装

composer install chrgriffin/laravel-defer

此包支持自动发现,所以如果你使用Laravel 5.6或更高版本,你就完成了!

如果不是,你需要将服务提供者添加到你的config/app.php中的providers数组中

ChrGriffin\LaravelDefer\LaravelDeferServiceProvider

你也可以将外观添加到你的别名数组中,这可能有助于

'LaravelDefer' => ChrGriffin\LaravelDefer\Facades\LaravelDefer::class

你还可以将配置发布到你的config文件夹

php artisan vendor:publish

使用

安装后,你可能需要清除你的编译视图

php artisan view:clear

现在加载任何页面,你可能会看到没有任何图片 - 这是因为你需要包含显示它们的脚本。你可以使用包类或Blade指令

@deferJS

// or:

echo ChrGriffin\LaravelDefer\LaravelDefer::js();

默认情况下,js()方法将输出一个名为loadDeferredImages()的JavaScript函数,该函数被<script>标签包围。你可以在配置文件中更改此行为

return [
    'function_name'    => 'bananas',
    'with_script_tags' => false
];

你还可以在应用程序代码中更改此行为(这将覆盖任何配置)

LaravelDefer::setFunctionName('bananas');
LaravelDefer::setWithScriptTags(false);

最后一步是在JavaScript中的任何需要位置调用loadDeferredImages()方法(或你为其命名的任何方法)。

$(document).ready(function () {
    loadDeferredImages();
});

跳过模板或图片

在配置文件中,你可以指定在编译时跳过的Blade模板

'ignored_paths' => [
    '/resources/views/mail', // this will skip all Blade templates inside the mail folder
    '/resources/views/nope.blade.php' // this will skip this specific template
],

你还可以指定在编译时跳过的特定图片

'ignored_images' => [
    'https://i.warosu.org/data/vr/img/0021/46/1420008946756.jpg', // this will skip this particular image
    'https://i.warosu.org/', // this will skip all images from this URL
    '1420008946756.jpg' // this will skip any image with this filename
],

内部机制

此包扩展了应用程序的Blade编译器。自定义编译器查找所有的<img>标签,并将它们的src属性移动到data-ldsrc属性中。稍后,loadDeferredImages()方法找到所有具有此属性的元素,并将其移回src属性。