Repository navigation
Require WP 6.3 and use core HTML and loading APIs - #1400
utkarshcloudinary wants to merge 8 commits into
Conversation
readme.txt already declares WordPress 6.3 as the minimum. Add the same "Requires at least" and "Requires PHP" headers to the plugin file, so WordPress blocks activation on older sites. Remove the code paths that only ran on WordPress versions below 6.3: the function_exists() checks for wp_get_original_image_path/url, has_block and wp_print_inline_script_tag, the get_post_parent() fallback, the pre-5.9 class-http.php include and the pre-5.1 render_block fallback for video blocks. The fallback callback stays, marked deprecated, for third-party callers. Use wp_admin_notice() (WP 6.4+) for the PHP version notice when it is available.
Replace shortcode_parse_atts() and str_replace() tag handling with WP_HTML_Tag_Processor (WP 6.2+). - Utils::parse_html_tag() reads the tag name and attributes with the HTML API. Values are decoded and not unslashed, and a ">" inside a value no longer cuts the tag short. Delivery::parse_element() and Utils::get_tag_attributes() use it. - Filter::add_front_end_attributes() sets the missing class with set_attribute(), instead of inserting text before "/>", which did nothing on tags without a self-closing slash. - The content filter no longer stores loading="lazy" in post content. The check called wp_lazy_loading_enabled with the wrong arguments, and a stored value stops core from finding above the fold images. - Remove the old srcset before wp_image_add_srcset_and_sizes(), which appends a second srcset instead of replacing the first one.
Cloudinary lazy load replaced every image with a placeholder, including the LCP image, which delays the largest paint. Follow the WordPress 6.3 loading optimization decisions instead: - An image with fetchpriority="high" is the LCP candidate and is never lazy loaded, so core's fetchpriority now takes effect. - An image with loading="lazy" or fetchpriority="low" is below the fold and is lazy loaded. - Other images count towards wp_omit_loading_attr_threshold (3 by default) in document order. The first ones load eagerly. The new cloudinary_lazy_load_in_initial_viewport filter can change the result per image. Delivery rebuilds the tag after core adds sizes="auto" (WP 6.7+), so run wp_img_tag_add_auto_sizes() on the rebuilt tag to keep it. The breakpoints e2e fixture now marks its image loading="lazy", as it is the only image in the post and would otherwise load eagerly.
The HTML API parser keeps backslashes in attribute values, which shortcode_parse_atts() used to strip. update_post_meta() unslashes the value, so the cached replacement for alt="C:\new" was saved as alt="C:new" and a cached page rendered a different tag than an uncached one. Slash the replacements before they are saved, and move the write into Delivery::update_context_cache() so it can be tested.
The breakpoints fixture image is now natively lazy loaded, and Delivery keeps the "auto" that WordPress 6.7+ adds to the sizes of lazy loaded images. Update the expected sizes attribute.
- Video blocks: replace the src and poster through the HTML API in the new Video::replace_tag_urls(). get_tag_attributes() now returns decoded values, so str_replace() missed URLs with "&" in the HTML and left the local URL when the Cloudinary player is off. - Stop loading the plugin on WordPress below 6.3 and show a notice. The header only blocks activation from the admin, not updates with Composer or a zip file. - Clear the replacement cache on cloudinary_version_upgrade. Cached tags skip rebuild_tag(), so pages kept the old markup. - Check the lazy load bypass classes before the viewport check, so bypassed images do not use up the eager places. - Call _deprecated_function() in the deprecated video callback. - Move remove_tag_attribute() to Utils. - Tests: skip the sizes="auto" test before WP 6.7, compare attributes instead of exact markup, parse tags through get_media_tags(), cover the new code, and add an e2e case for the first image.
|
Hello @gabrielcld2, Which version will this PR ship in? The PR adds a new filter ( |
|
@PatelUtkarsh We can include this in the |
The new lazy load filter and the deprecated video callback ship in 3.4.0, not 3.3.10.
gabrielcld2
left a comment
There was a problem hiding this comment.
This is looking good. left some comments
| $has_cache = array(); | ||
| $has_cache[ $type ] = $replacements; | ||
| update_post_meta( get_the_ID(), self::META_CACHE_KEY, $has_cache ); | ||
| $this->update_context_cache( $type, $replacements ); |
There was a problem hiding this comment.
The above-the-fold decision depends on where the image sits on the page, but the result ends up in this cache, keyed only by the original tag. get_context_cache() then merges the caches of every post that went through the_post, so a decision made on one page gets reused on another:
- Archives / blog home: each post's cache comes from its singular view, where its first image was eager. On an archive with 10 posts, the first image of post 8 is still served eager (no placeholder), even though it is far below the fold.
- Related posts / query loops on a singular page: the same thing happens for the posts in the loop.
- Mixed cached/uncached: cached tags skip
rebuild_tag(), so they never incrementviewport_count. An uncached image further down the page starts counting from 0 and can be made eager too.
Before this PR the lazy/eager result didn't depend on position, so caching the rebuilt tag was safe. Now it isn't.
A few options:
- Keep the viewport decision out of the cache. For example, cache the lazy version and apply the eager bypass when the replacements are applied.
- Don't cache
imgtags that went through the viewport check (simple, but we lose some of the cache benefit). - Only apply the viewport check when the cache we read was written for the current post (
is_singular()and the current queried object).
I don't mind which. What do you think?
There was a problem hiding this comment.
Thanks, you're right. I had checked this on the blog home before, but only for images core marks loading="lazy" on the archive, where the tag differs and so does the cache key. Your case, where core leaves the tag the same and only our count differs, does leak.
Fixed in b6f8c3f with a mix of your options 1 and 2:
- With the change for your other comment, an image core processed is decided from its own markup (
fetchpriority,loading, or core'sdecoding="async"with noloading). The tag is the cache key, so that decision is safe to cache: when core decides differently on another page, the tag differs too. - Only the tags counted towards the threshold, and the tags whose result the
cloudinary_lazy_load_in_initial_viewportfilter changed, depend on the page. Those are now left out of_cld_replacements, so they are rebuilt on every page. That should also cover the mixed cached/uncached case, as a counted tag is never read from the cache, so it is always counted (I haven't tested that case separately).
Checked on the local site, with the post's cache cleared, then written by a visit to the single post: the blog home listing that post rendered exactly the same eager/lazy result as before the cache existed. Note this post's content images all come through core, so none of them is counted; the "counted tags are left out" part is covered by test_replacement_cache_skips_position_dependent_tags, not by this check.
| } elseif ( 'lazy' === $loading || 'low' === $fetchpriority ) { | ||
| $in_viewport = false; | ||
| } else { | ||
| $in_viewport = $this->viewport_count < wp_omit_loading_attr_threshold(); |
There was a problem hiding this comment.
Question about the counting. This runs on the full output buffer, so header and template images (logo, site header image, menu icons…) use up the threshold before the content is reached. Core already made its own decision for the content images it processed: the first ones have no loading attribute and the rest got loading="lazy".
So with the default threshold of 3, a theme with a logo and two header images would lazy-load the first content image, which core had decided to load eagerly. In that case we do the opposite of what core decided, while the description says we use "the same signals as core".
Should an image with no loading attribute that core has already processed (e.g. it has a wp-image-* class and came through wp_filter_content_tags()) just be treated as eager, with the threshold counting used only for images core never saw? Or is it a deliberate choice to count document order across the whole page? Either way, a short note in the docblock would help.
There was a problem hiding this comment.
Good catch, that wasn't deliberate. Fixed in b6f8c3f as you suggested: an image core already processed and left without a loading attribute is treated as eager, and doesn't count towards the threshold. Only images core never saw are counted.
To tell them apart I used core's decoding attribute instead of the wp-image-* class: by default core adds decoding="async" to the images it processes (wp_filter_content_tags() and wp_get_attachment_image()), and only decides loading for images with a width and height. If a site removes decoding with the wp_img_tag_add_decoding_attr filter, its images just fall back to being counted. So decoding + width + height + no loading means core left it eager. One exception: when wp_lazy_loading_enabled is off, core adds no loading anywhere, so those images are counted as before.
Checked with two header images printed on wp_body_open before the content, threshold 3:
- before: the header images took two of the three eager places, so the third content image, which core had left without
loading, was lazy loaded. - after: that image is eager. The header images are still eager, and the images core lazy loaded are still lazy.
The docblock of is_in_initial_viewport() now lists these rules.
| $parsed['atts'][] = $name; | ||
| continue; | ||
| } | ||
| $parsed['atts'][ $name ] = (string) $value; |
There was a problem hiding this comment.
Nit / edge case: values are now decoded here, and HTML::build_tag() writes them back with esc_attr(), which does not double-encode existing entities. So a value that contains entity text gets decoded one level too far on the round trip. For example, alt="Use &lt;img&gt;" (an alt text that literally shows <img>) is decoded to Use <img>, and esc_attr() keeps it as is, so the browser now shows Use <img>.
It's a rare case and I wouldn't block on it, but since rebuild_tag() writes every attribute back, it might be worth either encoding the decoded values with double-encoding on (htmlspecialchars( $value, ENT_QUOTES, 'UTF-8', true )) when the tag is rebuilt, or adding a line about it in the Merge Danger section next to the backslash note.
There was a problem hiding this comment.
Agreed, fixed in b6f8c3f. rebuild_tag() and process_featured_image() now escape the attribute values that are unchanged from the original tag with double encoding on (Utils::escape_original_attributes()), so alt="Use &lt;img&gt;" comes out the same as it went in. Values another filter changed (e.g. on cloudinary_pre_image_tag) are left as they are, as they may already be escaped, and so are values with no &.
There are 6 new unit tests across the three fixes. On the previous commit, 5 fail; the sixth (test_missing_loading_attribute_only_counts_as_core_decision_when_core_decided) guards the fallback case and passes on both. Unit tests (148), phpcs, PHPStan and the image, video, asset edit and breakpoints e2e specs (10 tests) pass locally.
- Treat an image core processed and left without a loading attribute as eager, without counting it. Core adds decoding="async" to every image it processes and only decides the loading of images with a width and height. Only images core never saw, such as header and template images, count towards the threshold. Before, a logo and header images used up the threshold and the first content image was lazy loaded against core's decision. - Leave the counted tags, and tags whose result the viewport filter changed, out of the replacement cache. Their result depends on the page, and the cache of one post is reused on archives and loops. - Escape attribute values that are unchanged from the original tag with double encoding on, so a value showing entity text, such as alt="Use &lt;img&gt;", is not decoded one level too far.
Summary
Sets WordPress 6.3 as the minimum version (
readme.txtalready says 6.3) and uses the core APIs that this makes available.Lazy load no longer replaces images at the top of the page. It uses the same signals as core (6.3):
Cleanup: removes the fallbacks for WP versions below 6.3 (
function_exists()guards, theget_post_parent()fallback, theclass-http.phpinclude, the pre-5.1render_blockvideo fallback).filter_video_block_render_block()stays for third-party callers, deprecated since 3.4.0 with_deprecated_function(). On WP below 6.3 the plugin does not load and shows an admin notice (wp_admin_notice()when available), as the header alone does not stop updates through Composer or a zip file.Not included: the Interactivity API (needs 6.5 and a gallery/player rewrite) and
wp_admin_notice()for the plugin's own notice UI (that UI has icons and timed dismiss, which core does not support).Approach
>in a value is now skipped, instead of being rebuilt into broken markup.Lazy_Load::bypass_lazy_load(), andsizes="auto"on rebuilt tags.update_post_meta(). Because the parser now keeps backslashes, a cached page renderedalt="C:\new"asalt="C:new"while the uncached page did not. A regression test covers it (fails without the fix).sizes="auto"on its lazy image.src/posterare replaced through the HTML API (Video::replace_tag_urls()). The decoded values no longer matched&in the raw HTML.cloudinary_version_upgrade, so sites with cached pages get the new markup after the update.Evidence
The same parser code, run against the WP 6.3
WP_HTML_Tag_Processor:Class insertion on a tag without a self-closing slash:
<img src="a.jpg">stays unchanged (there is no/>to replace)<img class="wp-image-12" src="a.jpg">sizeson a rebuilt lazy image (WP 7.2 RC4):sizes="(max-width: 300px) 100vw, 300px"(core'sautowas dropped when the tag was rebuilt)sizes="auto, (max-width: 300px) 100vw, 300px"New unit tests are in
tests/phpunit/tests/test-wp-core-apis.php,test-delivery-parse-element.phpandtest-video-replace-urls.php. A new e2e case checks that the first image with no loading hint is not lazy loaded. They cover the parser, the class insertion, the srcset removal, the viewport threshold and core hints, and the new filter.Browser check (Chrome DevTools, local wp-env, WP 7.2 RC4, lazy load on, 6 synced images, image 5 has
fetchpriority="high"):developfetchpriority="high")loading="lazy")fetchpriority="high")wp_omit_loading_attr_threshold= 1: only the hero is eager.cloudinary_lazy_load_in_initial_viewport= false: all lazy, same asdevelop.developdrops core'ssizes="auto"from lazy images; this branch keeps it. Each image has onesrcset.QA notes
loadingattributes. On the front end, the first 3 images (default threshold) have a Cloudinarysrcand nodata-cloudinary="lazy". The later images have the placeholder and lazy load on scroll.add_filter( 'wp_omit_loading_attr_threshold', fn() => 1 );. Only the first image loads eagerly.fetchpriority="high"and is never a lazy placeholder.add_filter( 'cloudinary_lazy_load_in_initial_viewport', '__return_false' );. All images are lazy loaded again, as ondevelop.sizes="auto, …"on WP 6.7 or higher, and each image has only onesrcset.srcorposterURL with a query string (?a=1&b=2) is changed to the Cloudinary URL.Merge Danger
Door: two-way. No data or option changes. A revert restores the old behaviour. Content saved after this change no longer contains
loading="lazy", which is the core default.Blast Radius: front end markup of every image that Delivery rewrites.
wp_omit_loading_attr_thresholdorcloudinary_lazy_load_in_initial_viewport.cloudinary_parse_element/cloudinary_pre_image_tagfilters that expected the old output can see different values.