DEV Community

Discussion on: 3 easy steps to fix slow image loading

Collapse
 
matthewbdaly profile image
Matthew Daly

I would also add that caching images for as long as possible is prudent, particularly if you're using a CDN. If an image may change in future, you can use various cache-busting techniques to replace the image even if it is cached for a long time.

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);
    }
}
Collapse
 
felixhaeberle profile image
Felix Häberle

You're right! That could also be added here, thanks for pointing it out. :)