Skip to content

[12.x] Allow limiting number of assets to preload #55618

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,31 @@

class AddLinkHeadersForPreloadedAssets
{
/**
* Configure the middleware.
*
* @param int $limit
* @return string
*/
public static function using($limit)
{
return static::class.':'.$limit;
}

/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $limit
* @return \Illuminate\Http\Response
*/
public function handle($request, $next)
public function handle($request, $next, $limit = null)
{
return tap($next($request), function ($response) {
return tap($next($request), function ($response) use ($limit) {
if ($response instanceof Response && Vite::preloadedAssets() !== []) {
$response->header('Link', (new Collection(Vite::preloadedAssets()))
->when($limit, fn ($assets, $limit) => $assets->take($limit))
->map(fn ($attributes, $url) => "<{$url}>; ".implode('; ', $attributes))
->join(', '), false);
}
Expand Down
43 changes: 43 additions & 0 deletions tests/Http/Middleware/VitePreloadingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,47 @@ public function testItDoesNotOverwriteOtherLinkHeaders()
$response->headers->all('Link'),
);
}

public function testItCanLimitNumberOfAssetsPreloaded()
{
$app = new Container;
$app->instance(Vite::class, new class extends Vite
{
protected $preloadedAssets = [
'https://laravel.com/first.js' => [
'rel="modulepreload"',
'foo="bar"',
],
'https://laravel.com/second.js' => [
'rel="modulepreload"',
'foo="bar"',
],
'https://laravel.com/third.js' => [
'rel="modulepreload"',
'foo="bar"',
],
'https://laravel.com/fourth.js' => [
'rel="modulepreload"',
'foo="bar"',
],
];
});
Facade::setFacadeApplication($app);

$response = (new AddLinkHeadersForPreloadedAssets)->handle(new Request, fn () => new Response('ok'), 2);

$this->assertSame(
[
'<https://laravel.com/first.js>; rel="modulepreload"; foo="bar", <https://laravel.com/second.js>; rel="modulepreload"; foo="bar"',
],
$response->headers->all('Link'),
);
}

public function test_it_can_configure_the_middleware()
{
$definition = AddLinkHeadersForPreloadedAssets::using(limit: 5);

$this->assertSame('Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets:5', $definition);
}
}