Search code examples
javascriptdayjs

Why is DayJs Causing Site to Freeze and Not Load?


So, I have a site that requires day.js, and I've had some experience on previous sites, and it's worked fine, and loaded fast. But as soon as I try to use it on a new site, it just causes it my site to freeze up. I've tried using defer and async but it just won't work. I've used a local file, and it still won't work. I used Chrome DevTool's Network Panel, and it says everything sent a 200 OK response, so I don't know what to do.

let start=dayjs().startOf("day").add(2,"day")
while(start.$d!=0){start=start.subtract(1,"day")}
document.write(start)
<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>repl.it</title>
 <script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js" async></script>
 <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500,600" rel="stylesheet">
 <link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
 <script src="script.js"></script>
</body>
</html>

Here a demo is, it won't load here either. Eventually, it just says the page is unresponsive, and to wait or close it.


Solution

  • The problem is that the property $d is the date string, something like Sun May 02 2021 00:00:00. I think you're looking for $D, which is the day, something like 4. Additionally, you wait until the date is 0, but that can't happen because dates start on the first day of the month. You could instead do start = start.date(1) which would instantly set the date to 1 without using loops.

    The official docs can be found here.