cms
cms copied to clipboard
Bugfix/17653 assets transforms and eager loading
Description
Part 1:
Adjusts Asset::getUrlsBySize() (which is used by Asset::getSrcset()) to get the base size (from the transform or original image, if there’s no transform defined) and all the requested sizes, and calls Craft::$app->getImageTransforms()->eagerLoadTransforms() with that info.
Part 2:
Allows true to be passed to withTransforms(). If that’s the case, all the image transforms for the provided assets will be eager loaded.
Both options keep the number of DB queries independent of the number of needed sizes/transforms (once the transforms have been created).
Code examples:
- this was already possible
{# 36 db calls for the entire page once the transforms have been created
vs 43 without passing true to withTransforms or not including it at all #}
{% set myImages1 = craft.assets.id([165, 188]).withTransforms([{width: '240'}, '360w', '480w', '600w', '720w', '840w', '960w', '990w', '1100w']).all() %}
{% for myImage in myImages1 %}
{{ myImage.getSrcset([240, 360, 480, 600]) }}
{% endfor %}
- example for part 1 (
getSrcset()that preloads all existing image transform indexes)
{# 37 db calls for the entire page once the transforms have been created
vs 43 without preload param #}
{% set myImages3 = craft.assets.id([165, 188]).all() %}
{% for myImage in myImages3 %}
{{ myImage.getSrcset([240, 360, 480, 600], preload: true) }}
{% endfor %}
- example for part 2 (use
withTransforms(true)to preload all existing image transform indexes
{# 36 db calls for the entire page once the transforms have been created
vs 43 without passing true to withTransforms or not including it at all #}
{% set myImages2 = craft.assets.id([165, 188]).withTransforms(true).all() %}
{% for myImage in myImages2 %}
{{ myImage.getSrcset([240, 360, 480, 600]) }}
{% endfor %}