DEV Community

Discussion on: 3 easy steps to fix slow image loading

Collapse
 
catalin560 profile image
catalin560

would you mind explaining a few of those cache-busting techniques?

Collapse
 
matthewbdaly profile image
Matthew Daly

Basically, the idea is that you append a query string to the URL for an asset, usually based on the timestamp when it was last changed. That way, if you replace an image or other asset, the URL used in the application will change, and so you load the new version, no matter how long the old version was cached for.

Many frameworks and CMS's provide this functionality out of the box, such as the version() method in Laravel Mix. If yours doesn't it's not hard to roll your own. Here's a simple example of a Twig filter that does this:

<?php declare(strict_types=1);

namespace App\Views\Filters;

final class Version
{
    public function __invoke(string $path): string
    {
        return DIRECTORY_SEPARATOR . $path . "?v=" . filemtime(PUBLIC_DIR . DIRECTORY_SEPARATOR . $path);
    }
}