Skip to content

Commit

Permalink
document usage of frontend.js files
Browse files Browse the repository at this point in the history
  • Loading branch information
Vicente Canales committed Mar 23, 2021
1 parent 681fd1a commit 6f5d841
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions packages/block-library/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,63 @@ npm install @wordpress/block-library --save

_This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for ES2015+ such as lower versions of IE then using [core-js](https://github.com/zloirock/core-js) or [@babel/polyfill](https://babeljs.io/docs/en/next/babel-polyfill) will add support for these methods. Learn more about it in [Babel docs](https://babeljs.io/docs/en/next/caveats)._

## Building JavaScript for the browser

If a `frontend.js` file is present in the block's directory, this file will be built along other assets, making it available to load it from the browser.

This enables us to, for instance, load this file when the block is present on the page in several ways:

1. Using the block's `render_callback`:

```php

function render_my_block() {
$script_path = __DIR__ . '/block-name/frontend.js';

if ( file_exists( $script_path ) ) {
wp_enqueue_script(
'my_block_frontend_script',
plugins_url( 'frontend.js', $script_path ),
array(),
false,
true
);
}
}

function register_block_my_block() {
register_block_type_from_metadata(
__DIR__ . '/block-name',
array(
'render_callback' => 'render_my_block',
)
);
}


add_action( 'init', 'register_block_my_block' );
```

2. Using the `render_block` filter:

```php
function render_my_block() {
$script_path = __DIR__ . '/block-name/frontend.js';

if ( file_exists( $script_path ) ) {
wp_enqueue_script(
'my_block_frontend_script',
plugins_url( 'frontend.js', $script_path ),
array(),
false,
true
);
}
}

apply_filter( 'render_block', 'render_my_block' );
```

## API

<!-- START TOKEN(Autogenerated API docs) -->
Expand Down

0 comments on commit 6f5d841

Please sign in to comment.