Those who don't know about barba.js, Barba.js is a small (7kb minified and compressed) and easy-to-use library that helps you create fluid and smooth transitions between your website’s pages. It makes your website run like a SPA (Single Page Application) and help reduce the delay between your pages, minimize browser HTTP requests and enhance your user’s web experience.
I am using barba.js for this website Visit Suruga and it is performing really well. You can visit the website and check how the smooth transitions are working.
But everything isn't perfect. Same goes for barba.js.
Lets see how barba.js works:
Barba.js follows a specific DOM structure.
<body data-barba="wrapper">
<!-- put here content that will not change
between your pages, like <header> or <nav> -->
<main data-barba="container" data-barba-namespace="home">
<!-- put here the content you wish to change
between your pages, like your main content <h1> or <p> -->
</main>
<!-- put here content that will not change
between your pages, like <footer> -->
</body>
Barba.js will only update the contents which are inside the data-barba="container"
. Other parts of this DOM will remain the same what we had during the page load.
For this feature we have to load all the scripts, styles, libraries during the page load. Even if that page isn't using those style or script, which eventually make the initial page loading a bit slower.
Normally almost all pages has the same style and scripts needed. But there are few pages which requires extra libraries or styles. If we don't load those libraries the functionality will not work on those pages.
To fix this issue we took the advantage of the data-barba-namespace
attribute. Normally it is used for Transition rules and Views.
So we set the page name spot
in the data-barba-namespace
value in that page. And we also did added the library scripts in the bottom of the page (If we load the page first time). And after that based on the namespace value we added the same script inside barba hook.
barba.hooks.enter((data) => {
if (data.next.namespace === 'spot') {
// Initialize library
}
});
By doing this even if we go to the spot
page after transition from another page the library will be initialized in the page. So there will be no more error and the initial loading time of the index page will be reduced.
That's all for today. Thank you for reading!
Top comments (0)