You can eager-load elements that were already loaded (like an Entry or Product that Craft set up for you "outside" a template) like this:
{% do craft.app.elements.eagerLoadElements(
className(product),
[product],
[
['variants.variantImage', { withTransforms: ['thumbnail'] }],
]
) %}
This will load + set any downstream elements, just as though you'd used itchained an equivalent .with()
on the original query.
A couple notes:
className()
is used to capture the fully-qualified name of the Element class. It's required to let Craft know what kind of eager-loadable properties the specific Element Type has;[product]
is an array, because eager-loading is always done in "bulk," even for a single source element;
You can do a similar thing directly on the Variants, if you've got a reference to them, already:
{% set variants = product.variants %}
{% do craft.app.elements.eagerLoadElements(
className(variants | first),
variants,
[
['variantImage', { withTransforms: ['thumbnail'] }],
]
) %}