javascriptajaxinitializationbarbajs

barba js v2 reinit main.js script


I am struggling with barba js v2. After ajaxtransition my main.js script stops working. I would like to reinit this script somehow ...

I have simple barba transition like this ->

import barba from "@barba/core"

class Transition {
  constructor() {
    // console.log(barba)
    this.events()
  }

  events() {
    // console.log("events")
    barba.init({
      transitions: [
        {
          name: "default-transition",
          leave() {
            // create your stunning leave animation here
            console.log("leave")
          },
          enter() {
            console.log("enter")
            // create your amazing enter animation here
          }
        }
      ]
    })
  }
}

export default Transition

and at the and of </body> tag I have

    <script src="js/main-dist.js"></script>
  </body>

Inside this main-dist.js script there are couple of other scripts that are imported, for example a function that shows current date.

When I go to the page at first time, everything works fine, but when I go to another page and come back to the page that should display the current date, the date is not displaying because script is not initialized. It initalizes only on load not on ajaxload.

So my roadblock is to re-init somehow this script on ajaxload.


Solution

  • I figured it out. There is barba hook "after" that we can use in the transition script :)

    barba.hooks.after(() => {
    const bottomDOM = document.getElementsByTagName("body")[0]
    const newScript = document.createElement("script")
    const oldScript = document.querySelector(".main-script")
    newScript.src = "js/main-dist.js"
    newScript.className = "main-script"
    oldScript.remove()
    bottomDOM.appendChild(newScript)
    })
    

    I have a <script class="main-script" src="js/main-dist.js"></script> at the end of the DOM, and use barba.hook to remove it and then add it again