skip to Main Content

I have a NextJS website and I want to add a Splash Screen for before website is loaded

but because the Splash Screen is also in the NextJS code, it will loading when nextjs rendered on the server and the JS downloaded and executed on the client. in fact, it’s useless because it will execute after the page is ready!

how can I do the Splash Screen before react completely loaded and executed ?

I also use nginx for proxy_pass

4

Answers


  1. use this code

    useEffect(() => {
            const handleStart = () => { setPageLoading(true); };
            const handleComplete = () => {
                     setPageLoading(false);
            };
            router.events.on('routeChangeStart', handleStart);
            router.events.on('routeChangeComplete', handleComplete);
            router.events.on('routeChangeError', handleComplete);
        }, [router]);
    

    and use pageLoding for show splash

    Login or Signup to reply.
  2. For loading screen:

    import React from 'react'
    import useSWR from 'swr'
    const fetcher = (url) => fetch(url).then((res) => res.json());
    
    // your main function
    export default function Profile() {
      //for relative and absolute paths
      const { data, error } = useSWR('/api/user', fetcher)
    
      if (error) return <div>failed to load</div>
      //for the loading you can create your custom component and insert instead of div, like this you keep same styling
      if (!data) return <div>loading...</div>
      if (data) return <div>hello {data.name}!</div>
    }
    

    Don’t use useEffect hook, use this lib, better code and functionnality.

    Login or Signup to reply.
  3. You have multiple possibility

    1. You can start your Next Application on a page that contain a simple shimmer(splash screen), then replace the URL by url that contain SSR, and finally remove loading page for indexing with robot.txt. You can read more about this tips there.

    2. You can insert inside on … tag a CSS to show a loader(your splash screen). Then when the SSR function will be in loading the loader will be hide but when the browser download index.html(first file loaded, that contain style tag) the loader will be show before the browser download another assets(images, js, etc) and load it. You can read more about this tips there

    The first tips will show loader fast than the second tip but require more steep(create another page, replace url, remove loader page for indexing)

    Login or Signup to reply.
  4. You can do it by using DOMContentLoaded event, here an example:

    In your _app.tsx and outside your function:

    if (typeof window !== "undefined") {
      document.addEventListener("DOMContentLoaded", () => {
        // your code here ..
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search