Uncaught ReferenceError: LazyLoad未定义问题求助(使用vanilla-lazyload)
Hey there, let's work through that frustrating error you're seeing with the vanilla-lazyload script. Here are the most common fixes to get it up and running:
1. Wait for the script to load before referencing LazyLoad
This error almost always happens because your code tries to use LazyLoad before the script has finished loading. Even with async=false, wrapping your initialization logic in the script's onload event guarantees you only access LazyLoad once it's fully available.
Update your code like this:
(function(w, d){ var b = d.getElementsByTagName('body')[0]; var s = d.createElement("script"); s.async = false; var v = !("IntersectionObserver" in w) ? "8.7.1" : "10.5.2"; s.src = "https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/" + v + "/lazyload.min.js"; // Initialize only after the script loads completely s.onload = function() { w.lazyLoadOptions = { // Add your custom options here (e.g., elements_selector: ".my-lazy-element") }; // Create a new LazyLoad instance if you're not relying on auto-initialization new LazyLoad(w.lazyLoadOptions); }; b.appendChild(s); })(window, document);
2. Verify auto-initialization requirements
Vanilla-lazyload automatically initializes for elements with the lazy class by default. If you're using a custom class name for your lazy elements, make sure you define it in lazyLoadOptions:
w.lazyLoadOptions = { elements_selector: ".your-custom-lazy-class" };
If you skip manual initialization (new LazyLoad()), double-check that your elements have the correct class name matching the selector.
3. Check if the script is loading successfully
Open your browser's DevTools (F12) and head to the Network tab. Filter by "JS" and reload the page. Make sure lazyload.min.js loads with a 200 OK status. If it's failing, double-check the URL (your version logic looks solid, but typos happen!).
4. Rule out version-specific quirks
The older 8.7.1 version (for browsers without IntersectionObserver) uses the same LazyLoad constructor, so that shouldn't be the issue—but if you're still stuck, try hardcoding the latest version temporarily to eliminate version-related bugs.
内容的提问来源于stack exchange,提问作者Adam

