1 year ago

#66822

test-img

Freddy

Reload inline and src defined scripts during AJAX page transition

I'm trying to implement barba.js on a HubSpot site.

Issue with HubSpot is that it renders our js related to forms or js related to custom modules within <script><script> tags.

As such, currently, with my barba implementation, if I transition over to a page with a HubSpot form for example, that form will not show and js related to my modules (such as slick js, they do not work either.

Using the hooks defined below (from the docs), I've added an ajax call to attempt to reload scripts that have a src defined. However, I cannot test if that is working because the js from my custom modules are not working.

Property Description
data.current Current page related
data.next Next page related
data.trigger Link that triggered the transition

Question being, is there a way for me to reload scripts without src defined?

Here is my current implementation:

function delay(n){
  n = n || 2000;
  return new Promise((done) => {
    setTimeout(() => {
      done();
    }, n);
  });
}

barba.init({
  sync: true,
  prefetchIgnore: true,
  debug: true,
  transitions: [{

    async leave(data){
      const done = this.async();
      await delay(200);
      done();
    },

    async beforeEnter({ next, container }) {
      $(container).find('script').each(function (i, script) {
        var $script = $(script);
        $.ajax({
          url: $script.attr('src'),
          cache: true,
          dataType: 'script',
          success: function () {
            $script.trigger('load');
          }
        });
      });
    },



    async enter(data){
      let scrollX = 0
      let scrollY = 0

      barba.hooks.leave(() => {
        scrollX = barba.history.current.scroll.x;
        scrollY = barba.history.current.scroll.y;
      });

      window.scrollTo(scrollX, scrollY);
    },

    async once(data){
      console.log("test");
    },

  }]
});

Here is a working demo

Follow these steps:

  1. Click on page 1. Notice how the HubSpot form loads.
  2. Click on page 2
  3. Notice how the slick slider module isn't working
  4. Now refresh page 2 and you will see slick is working.
  5. Navigate to page 1 and you'll see the form is not working now.

Visual of issue:

enter image description here

javascript

jquery

barbajs

0 Answers

Your Answer

Accepted video resources