Sergey Pervushin
Sergey Pervushin

Reputation: 373

WebP Express does not process images loaded via AJAX in WordPress

I am using the WebP Express plugin in WordPress, and it correctly replaces elements with tags when the page loads initially. However, when I load additional content via AJAX, the newly added images remain in their original format (.jpg or .png) and are not converted to WebP.

What I have tried:

  1. Manually triggering WebP Express after AJAX:
setTimeout(() => {
    document.dispatchEvent(new Event('DOMContentLoaded'));
}, 200);
  1. Using apply_filters('the_content', wp_get_attachment_image(...)) in PHP:
echo apply_filters('the_content', wp_get_attachment_image($pic['ID'], 'medium_large'));

How AJAX works in my setup:

My Question: How can I ensure that WebP Express processes dynamically loaded images after AJAX? Is there a way to force WebP Express to recognize and convert newly loaded images without manually modifying src attributes in JavaScript?

Any guidance would be greatly appreciated!

Upvotes: 1

Views: 41

Answers (1)

Sergey Pervushin
Sergey Pervushin

Reputation: 373

I found that WebP Express works correctly even without the <picture> tag. The reason is that my server is running Nginx with specific rules that serve WebP images directly at the server level, so WebP Express does not need to modify the HTML.

How WebP Express Works on My Setup

  • I'm using an Nginx server with custom rewrite rules that detect if the browser supports WebP and serve .webp images accordingly.
  • The "Alter HTML" option in WebP Express is completely disabled, meaning the plugin does not modify the HTML to use tags.
  • Even though HTML still references .jpg/.png, browsers actually receive .webp files due to server-side handling.

My Nginx WebP Rewrite Rules

# WebP Express rules
# --------------------
location ~* ^/?wp-content/.*\.(png|jpe?g)$ {
    add_header Vary Accept;
    expires 365d;
    if ($http_accept !~* "webp"){
        break;
    }
    try_files
        /wp-content/webp-express/webp-images/doc-root/$uri.webp
        $uri.webp
        /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content
        ;
}

# Route requests for non-existing webps to the converter
location ~* ^/?wp-content/.*\.(png|jpe?g)\.webp$ {
    try_files
        $uri
        /wp-content/plugins/webp-express/wod/webp-realizer.php?xdestination=x$request_filename&wp-content=wp-content
        ;
}
# ------------------- (WebP Express rules ends here)

How I Verified This

  • Checked the browser network requests (DevTools → Network → Img) - the HTML still shows .jpg/.png, but the browser actually loads .webp.
  • Tested in a browser that does NOT support WebP (e.g., Safari on iPhone 8) - the server correctly serves .jpg/.png when WebP is not supported.

Upvotes: 0

Related Questions