Brain-WP/Assets

Dequeue ability

Opened this issue · 4 comments

Nice code - not joking when I say it reduced my asset enqeueuing code by >50% and made it far more readable :D

For completeness though, it'd be nice to have a simple method for dequeuing an arbitrary asset. As an example, my theme spits out its own styles for a particular plugin, making the plugin styles useless. It'd be great to be able to dequeue the plugin styles through the class (for literally no other reason than pretty code)

$assets = Assets::forTheme();

$manifest = $assets
            ->enqueueScript('manifest', ['jquery'])
            ->useDefer()

$vendor = $assets
            ->enqueueScript('vendor', [$manifest])
            ->useDefer();

$app = $assets
            ->enqueueScript('vendor', [$vendor])
            ->useDefer();

// ew...
wp_dequeue_script('some-plugin-script');

// wow! :D
$assets->dequeue('some-plugin-script')

I could also see this being useful for conditional assets.

$assets = Assets::forTheme();

// enqueue a whole bunch of assets
foreach($myAssets as $key => $asset) {
  $myAssets[$key] =   $assets
      ->enqueueScript($asset, ['jquery'])
      ->useDefer();
}

// dequeue the not needed one. 
if ( ! get_field('fancy-page-intro', 'options) ) {
  // ability to pass in the asset object would be nice
  $assets->dequeue($myAssets['conditional-asset']);
}

You might want to check out https://github.com/inpsyde/assets a much more maintained project.

I had the exact same dequeue wish there inpsyde/assets#23 but couldn't figure out a sane implementation.

@mindfullsilence this is implemnted in v0.2.0 - see https://github.com/Brain-WP/Assets/releases/tag/0.2.0. If you are on WP 6.3+ and PHP 8.0+ you can use that. Be mindful there are breaking changes in the internal API, but not much (or not at all) in the consuming API.


@lkraav Yes, Inpsyde Assets is more actively maintained (mostly because is much more used), but there are differences with that library:

  • It has a "manager" that determines for you which hook to use to enqueue assets. Thta had generated issues with new hooks being added especially for Gutenberg. It also force tou to act at certain hook even for registering which WP allows tou to do very early
  • It has no method to just retrieve assets URLs
  • If you want to use manifest.json, it is pretty opinionated in the name you have to use for your assets, forcing you to use a specific naming convention if you don't want to use custom code
  • It has no concept of "debug mode" (e.g. to always return a fresh version)
  • It hasn't catch up (yet) with nw 6.3 API for async and defer script attributes, still using the "custom" approach

On the other hand, that library has more things this library has not:

Those are things that require custom code using this lib.

Tyvm for the update, we'll take a closer look!