Support

Account

Home Forums Gutenberg Block Assets (JS) runs before HTML content loaded

Unread

Block Assets (JS) runs before HTML content loaded

  • Ok, so I have an ACF issue. I am using blocks for the first time in a build. I have some JS that I am enqueue-ing for a carousel. I am trying to use it in both the backend and fronted, so I am using the enqueue_assets callback when registering my block. The frontend works perfectly, the issue is the backend. The files pull in properly, and with correct priority and dependencies. But the actual HTML content is not loaded early enough, so the JS does not see the selector I am trying to turn into the carousel. So then nothing happens. But if i put a 5 second timeout around the initialization of the carousel, it will work (don’t want to do this, it is just an example to prove the JS runs in the BE).

    Here is my registration block:

    acf_register_block_type(array_merge($defaults, [
        'name'              => 'events',
        'title'             => __('Events'),
        'description'       => __('A block for displaying Events.'),
        'enqueue_assets' => function(){
          wp_enqueue_script( 'carousel-script', '//unpkg.com/flickity@2/dist/flickity.pkgd.min.js', ['jquery'], '2.2', true );
          wp_enqueue_script( 'carousel', THEME_URI . '/dist/js/carousels.js', ['carousel-script'], null, true );
          wp_enqueue_style( 'carousel', '//unpkg.com/flickity@2/dist/flickity.min.css', [], '2.2', 'all' );
        },
        'keywords'          => [ 'events' ],
        'render_template'   => 'template-parts/block-template.php',
    ]));

    init JS in carousels.js:

    document.addEventListener(
      "DOMContentLoaded", () => {
        const events = document.getElementsByClassName('event-slider');
        let options = {
          selectedAttraction: 0.1,
          friction: 0.5,
          wrapAround: true,
          pageDots: false,
          prevNextButtons: false,
          adaptiveHeight: true,
        }
        if(events.length) {
          let eventsSlider = new Flickity(events[0], options);
          // Select Cell on Click
          eventsSlider.on( 'staticClick', ( e, pointer, el, index ) => {
            if ( index !== undefined ) {
              eventsSlider.select( index );
            }
          });
        }
      }
    );
Viewing 1 post (of 1 total)

The topic ‘Block Assets (JS) runs before HTML content loaded’ is closed to new replies.