{"id":121,"date":"2023-11-06T15:12:18","date_gmt":"2023-11-06T19:12:18","guid":{"rendered":"https:\/\/kylekelly.com\/?p=121"},"modified":"2023-11-06T15:14:34","modified_gmt":"2023-11-06T19:14:34","slug":"load-3rd-party-javascript-in-your-custom-block","status":"publish","type":"post","link":"https:\/\/kylekelly.com\/posts\/load-3rd-party-javascript-in-your-custom-block\/","title":{"rendered":"Load 3rd party JavaScript in your custom block"},"content":{"rendered":"\n

The best way I’ve found to use 3rd party JavaScript in my custom blocks (for example loading AlpineJS or VueJS) is to register the script and then use viewScript to include it.<\/p>\n\n\n\n

Here’s an example<\/h2>\n\n\n\n

In your custom block plugin PHP:<\/p>\n\n\n\n

add_action('wp_enqueue_scripts', function() {\n\t$plugin_url = plugin_dir_url( __FILE__ );\n\twp_register_script( 'script-name-goes-here', $plugin_url . \"script.min.js\", false, '1.0', true );\n});<\/code><\/pre>\n\n\n\n

Then in block.json <\/p>\n\n\n\n

\"viewScript\": ['script-name-goes-here']<\/code><\/pre>\n\n\n\n

Now that script will load on every page the block is included on, and only load once if the block is used multiple times on the page.<\/p>\n","protected":false},"excerpt":{"rendered":"

The best way I’ve found to use 3rd party JavaScript in my custom blocks (for example loading AlpineJS or VueJS) is to register the script and then use viewScript to include it. Here’s an example In your custom block plugin PHP: Then in block.json Now that script will load on every page the block is […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[4,9],"_links":{"self":[{"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/posts\/121"}],"collection":[{"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/comments?post=121"}],"version-history":[{"count":5,"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/posts\/121\/revisions"}],"predecessor-version":[{"id":127,"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/posts\/121\/revisions\/127"}],"wp:attachment":[{"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/media?parent=121"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/categories?post=121"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kylekelly.com\/wp-json\/wp\/v2\/tags?post=121"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}