Skip to content

Fallback script obsolete - remove it #996

@westonruter

Description

@westonruter

See discussion below where we decided we should drop the fallback script, especially since the plugin now supports the <picture> element which provides smoother fallback experience, and because WebP is so widely supported.

Old description for "Script handling in WebP Uploads can be improved"

Currently an inline script is printed to the page which conditionally loads a fallback.js script:

wp_print_inline_script_tag(
preg_replace( '/\s+/', '', $javascript ),
array(
'id' => 'webpUploadsFallbackWebpImages',
'data-rest-api' => esc_url_raw( trailingslashit( get_rest_url() ) ),
)
);

Note how it adds a data-rest-api data attribute here. This is then read in fallback.js via:

var restApi = document
.getElementById( 'webpUploadsFallbackWebpImages' )
.getAttribute( 'data-rest-api' );

This value is then used to construct the script URL to load:

var jsonp = document.createElement( 'script' );
var restPath =
'wp/v2/media/?_fields=id,media_details&_jsonp=wpPerfLab.webpUploadsFallbackWebpImages&per_page=100&include=' +
pageIds.join( ',' );
if ( -1 !== restApi.indexOf( '?' ) ) {
restPath = restPath.replace( '?', '&' );
}
jsonp.src = restApi + restPath;
document.body.appendChild( jsonp );

A couple things here:

  1. Wouldn't it be better to rely on fetch() than to use JSONP?
  2. Instead of exporting the URL in an HTML attribute, why not expose it via a global variable in the same inline script that is being printed to begin with?
  3. The query args for restPath would be better constructed with URLSearchParams, or if IE11 compat is really desired, fall back to using document.createElement('a').href.

Also, in that inline script it would be slightly safer if this line used wp_json_encode():

s.src = '<?php echo esc_url_raw( plugins_url( '/fallback.js', __FILE__ ) ); ?>';

Like:

s.src = <?php echo wp_json_encode( esc_url_raw( plugins_url( '/fallback.js', __FILE__ ) ) ); ?>; 

Lastly, instead of relying on data attributes on the script tag, the necessary data may make more sense to export into JS via wp_add_inline_script_tag() or else a JSON script. The reason is that the script tag for JS may end up getting concatenated with other scripts, resulting in those attributes getting lost.

Metadata

Metadata

Labels

[Plugin] Modern Image FormatsIssues for the Modern Image Formats plugin (formerly WebP Uploads)[Type] EnhancementA suggestion for improvement of an existing feature

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions