Constraint first
lossless (pixel-exact, verified), visually-lossless (SSIM ≥ 0.99) or balanced (SSIM ≥ 0.975). Every candidate is decoded and scored; nothing is returned on an estimate.
Encodes each image several ways in a Web Worker, measures every result, and keeps the smallest one that meets your lossless or SSIM constraint.