• Hi!

    For context, I’m running WordPress 6.4.2.

    I have created a dynamic block with the following block.json content (only showing relevant part here):

        },
    	"editorScript": "file:./index.js",
    	"editorStyle": "file:./index.css",
    	"style": "file:./style-index.css",
    	"render": "file:./render.php",
    	"viewScript": "file:./view.js"
    }

    I have added several JavaScript functions to view.js that are later used in the block.

    The script is loaded into the matching page like this:

    <script type="text/javascript" src="<websiteURL - redacted>/wp-content/plugins/xtradeb-launchpad-integration/build/xd-lp-package-details/view.js?ver=df18059b4cb4a722b872" id="xd-lp-package-details-xtradeb-launchpad-integration-view-script-js" defer="defer" data-wp-strategy="defer"></script>

    I can browse and see the script content in the browser. However, none of its functions seem to be available and I get errors like this:

    Uncaught ReferenceError: installButton is not defined
        at HTMLButtonElement.onclick (<post name - redacted>/:568:1336)
    onclick @ <post name - redacted>/:568

    If instead of using viewScript, I enqueue the same file as a dependency (here I renamed the file from view.js to details.js):

    wp_enqueue_script( 'xd-lp-details-js', plugin_dir_url( __FILE__ ) . 'includes/js/details.js', array(), '', true );

    The script is loaded like this into the page in roughly the same location:

    <script type="text/javascript" src="<websiteURL - redacted>/wp-content/plugins/xtradeb-launchpad-integration/includes/js/details.js?ver=4fd0f5bc13853fae144764d9c4a67c2c" id="xd-lp-details-js-js"></script>

    Now, all required functions are available and everything works as expected.

    Why can’t I use the block “viewScript”? Why doesn’t it work?

    What is the best way forward inline with best practices?

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • As you can see from the markup, the viewScript script is deferred, which means that its not loaded immediately, and may not be available yet when the browser parses the onclick attribute.

    The solution is not to bind the click event using the onclick attribute. Instead you should bind the event using addEventListener in your script. This means that your script can still work while using the more performant loading method. Additionally, in most cases the onclick attribute will be stripped from your post content entirely for security reasons if a non-Administrator makes a change to the post, as they are usually not allowed to include JavaScript in posts.

    Thread Starter jholiveira

    (@jholiveira)

    Thank you Jacob!

    Just for reference, this is the plugin I’m developing: xtradeb-launchpad-integration and I use it here: https://xtradeb.net.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘viewScript functions from dynamic block not available’ is closed to new replies.