简体   繁体   中英

javascript library works only after refreshing the page

So I'm using Swiper.js in order to swipe orizontally some content in my portfolio. If i open the page locally, everything works fine (I'm able to swipe, buttons are displayed,..) but if I open it on Netlify (free hosting service) I'm having an issue: buttons are displayed but I cannot swipe.

Refreshing the page, fix the problem.

In the head section i have links to CDN

<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css" />
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />

and the scripts are located right before the end of the body

<script src="https://unpkg.com/swiper/swiper-bundle.js"></script>
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>

In the console.log i have this error: "filed to load resource: the server responded with a status of 404" . Refreshing, again, fix the problem.

Do you guys know how to fix this problem?

That is because the library loads before the page and so it cannot locate elements in the DOM, since they don't exist yet.

Add a defer attribute to the script tag or place it at the end of the page.

<script defer src="..."></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM