Skip to content

Reconsider approach of using script dependencies to opt-in a script for worker offloading #1468

@westonruter

Description

@westonruter

Currently the way that a script is offloaded to a web worker is to add the web-worker-offloading script dependency:

add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script(
  	  'non-critical-js',
  	  '/path/to/non-critical.js',
  	  array( 'web-worker-offloading' ), // Note the `web-worker-offloading` being added as a dep
  	  '1.0.0',
  	  true
    );
} );

To opt-in existing scripts:

add_action( 'wp_print_scripts', function () {
	$scripts = wp_scripts();
	$handle  = 'foo';
	if ( array_key_exists( $handle, $scripts->registered ) ) {
		$scripts->registered[ $handle ]->deps[] = 'web-worker-offloading';
	}
} );

However, I just realized a significant problem: if someone deactivates the Web Worker Offloading plugin, then the web-worker-offloading script won't be registered and so the script having it asa dependency won't get printed at all. This would then necessitate having to add conditional checks like the following before doing the above code:

if ( defined( 'WEB_WORKER_OFFLOADING_VERSION' ) ) {
    // Now include the web-worker-offloading dependency.
}

We could make this more resilient by taking a similar approach to what we did with the script loading strategies (async/defer). In fact, offloading to a web worker could itself be considered a type of loading strategy. With script loading strategies, we utilize the strategy key for script data. So for example an existing script can be opted-in to the async strategy:

wp_script_add_data( 'foo', 'strategy', 'async' );

We could do something similar for offloading to a worker, for example:

wp_script_add_data( 'foo', 'worker', true );

Then when scripts are being printed, we could check if any of the pending handles have a worker script data key with a true value, and if so, print the Partytown script as well as add the type="text/partytown" attribute to the script being printed.

Metadata

Metadata

Labels

Type

No type
No fields configured for issues without a type.

Projects

Status

Done 😃

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions