Enqueuing Scripts And Using amp-bind

AMP doesn’t allow <script> tags, other than <script type="application/json"> (like in amp-bind). So this plugin will remove enqueued JavaScript files on AMP pages.

Using amp-bind can be an alternative to this. Here’s an example of how to replace these lines of JavaScript from the ‘underscores’ theme with amp-bind:

button.onclick = function() {
    if ( -1 !== container.className.indexOf( 'toggled' ) ) {
        container.className = container.className.replace( ' toggled', '' );
        button.setAttribute( 'aria-expanded', 'false' );
        menu.setAttribute( 'aria-expanded', 'false' );
    } else {
        container.className += ' toggled';
        button.setAttribute( 'aria-expanded', 'true' );
        menu.setAttribute( 'aria-expanded', 'true' );
    }
};

That snippets operates on the following lines from header.php. When the <button> is clicked, it toggles the aria-expanded attributes and a class.

<nav id="site-navigation" class="main-navigation"> <!-- container in JS file -->
    <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', '_s' ); ?></button> <!-- button in JS file -->
    <?php
    wp_nav_menu( array(
        'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', <!-- menu in JS file -->
        ...

The comments after the elements above show which JS variables refer to them. The items_wrap argument is added, as this needs to be able to change the <ul> element.

We can set an on attribute for the <button>:

on="tap:AMP.setState({primaryMenuExpanded: !primaryMenuExpanded})"

This will toggle the primaryMenuExpanded state. And the container, button, and menu will update based on that.

The aria-expanded attributes update based on the state:

[aria-expanded]="primaryMenuExpanded? 'true' : 'false'"

The final markup is:

<nav id="site-navigation" class="main-navigation" [class]="primaryMenuExpanded ? 'toggle main-navigation' : 'main-navigation'">
    <button on="tap:AMP.setState({primaryMenuExpanded: !primaryMenuExpanded})" class="menu-toggle" aria-controls="primary-menu" aria-expanded="false" [aria-expanded]="primaryMenuExpanded ? 'true' : 'false'"><?php esc_html_e( 'Primary Menu', '_s' ); ?></button>
    <?php
    wp_nav_menu( array(
        'items_wrap' => '<ul [aria-expanded]="primaryMenuExpanded ? \'true\' : \'false\'" id="%1$s" class="%2$s">%3$s</ul>',
        ...