在Laravel 8+中使用时,这是一种加载CSS或JS资源一次且仅一次的简单方法。

2.1.0 2023-01-31 11:12 UTC

This package is auto-updated.

Last update: 2024-09-04 17:28:41 UTC


README

Latest Version on Packagist Total Downloads Build Status StyleCI

将您的 <script src='file.js'><link href='file.css'> 标签替换为 @loadOnce('file.css')@loadOnce('file.js'),此包将确保CSS或JS在页面中仅加载一次。

安装

通过Composer

$ composer require digitallyhappy/assets

使用方法

使用此包提供的 @loadOnce() Blade指令替换您标准的CSS和JS加载HTML。

-    <script src="{{ asset('path/to/file.js') }}">
+    @loadOnce('path/to/file.js')

-    <link href="{{ asset('path/to/file.css') }}" rel="stylesheet" type="text/css">
+    @loadOnce('path/to/file.css')

此包提供了三个Blade指令,在99%的情况下您将使用 @loadOnce()

@loadOnce('path/to/file.css')
@loadOnce('path/to/file.js')
// depending of the file extension, the first time it will output
// <link href="{{ asset('path/to/file.css')" rel="stylesheet" type="text/css">
// or
// <script src="{{ asset('path/to/file.js')"></script>
// then the rest of the times this is called... it'll output nothing

// IN ADDITION, if you have an entire block of HTML that you want to only output once:

@loadOnce('unique_name_for_code_block')
    <script>
        <!-- Your JS here -->
    </script>

    <!-- OR -->

    <style>
        <!-- Your CSS here -->
    </style>
@endLoadOnce
// will output the contents the first time...
// then the second time it will just output nothing

但是,如果您想将一个 变量 作为参数传递,而不是一个 字符串,您会发现它不起作用,因为指令无法判断它是CSS、JS还是代码块。这就是我们创建 @loadStyleOnce()@loadScriptOnce() 的原因。

@php
    $pathToCssFile = 'path/to/file.css';
    $pathToJsFile = 'path/to/file.js';
@endphp

@loadStyleOnce($pathToCssFile)
// will output <link href="{{ asset('path/to/file.css')"> the first time
// then the second time this is called it'll output nothing

@loadScriptOnce($pathToJsFile)
// will output <script src="{{ asset('path/to/file.js')"></script> the first time
// then the second time this is called it'll output nothing

为什么这个包存在?

在Laravel 8+中,如果您的CSS或JS资源在blade文件中加载

// card.blade.php

<div class="card">
  Lorem ipsum
</div>

<script src="path/to/script.js"></script>

并且您在一个页面上多次加载该blade文件(例如,在页面上多次包含 card.blade.php),您将最终会在同一页面上多次加载该 script 标签。为了避免这种情况,Laravel 8提供了 @once 指令,该指令将只输出一次内容,无论该blade文件加载了多少次。

// card.blade.php

<div class="card">
  Lorem ipsum
</div>

@once
<script src="path/to/script.js"></script>
@endonce

但是,如果您的 script.js 文件不仅由 card.blade.php 加载,还由其他blade模板(例如,同一页面上加载的 hero.blade.php)加载,那么如果您使用的是 @once 指令,您将再次遇到相同的问题 - 同一个脚本在同一个页面上加载多次。

这就是此包发挥作用的地方。它将资源只加载一次,即使它从多个blade文件中加载。

变更日志

有关最近更改的更多信息,请参阅变更日志

测试

$ composer test

贡献

有关详细信息和一个待办事项列表,请参阅contributing.md

安全性

如果您发现任何与安全性相关的问题,请通过电子邮件 hello@tabacitu.ro 而不是使用问题跟踪器。

致谢

许可证

MIT。有关更多信息,请参阅许可证文件