1

In a Laravel 9 project I am loading Glide.js via my app.js file:

import "./bootstrap";
import flatpickr from "flatpickr";
import Alpine from "alpinejs";
import Glide from "@glidejs/glide";

window.Alpine = Alpine;
window.flatpickr = flatpickr;
Alpine.start();

If I initialise the Glide object in the same file with:


new Glide(".glide", {hoverpause:true, autoplay:2000}).mount();

It works ok on the page I want it on, however it stops Alpine working on other pages. I assumed that by adding it to the Window object

window.Glide = Glide;

I could simply declare it on the page I want it but I get the

Uncaught ReferenceError: Glide is not defined error.

I've also tried importing via cdn in a script tag placed on my home view

   <script src="https://unpkg.com/@glidejs/glide@3.6.0/dist/glide.js"></script>
    <script>
        new Glide(".glide", {
            hoverpause: true,
            autoplay: 2000,
            perView: 3,
        }).mount();
    </script>

But this tells me that [Glide warn]: Root element must be a existing Html node and doesn't work either.

Js isn't my strong suit by a long shot and I have a lot to read up on and learn but would somebody be so kind as to give me some pointers?

Thanks in advance.

prevailrob
  • 275
  • 3
  • 11
  • 1
    in your app.js check if the `.glide` element exists before creating the new glide instance (e.g. `document.querySelector('.glide') !== null` . In pages where it doesn't exist it likely errors and prevents the rest of the JS code from running. Personally I would avoid putting things in the `window` object if possible since it can get really bloated really fast – apokryfos Jan 04 '23 at 11:46
  • Thank you, that works. Like I said I don't use js very open and my knowledge is very sparse. It hadn't even occured to me to do that but now it seems totally obvious. I will add it as an answer for anyone stumbling on this question in the future. – prevailrob Jan 04 '23 at 13:08

1 Answers1

1

I solved this issue by only instanciating the Glide object if the target element exists.

if (document.querySelector(".glide") !== null) {
    new Glide(".glide", {
        hoverpause: true,
        autoplay: 2000,
        perView: 3,
    }).mount();
}
prevailrob
  • 275
  • 3
  • 11