最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to ensure that page has finished loading on a React site - Stack Overflow

programmeradmin0浏览0评论

Is there a way to make sure that a web page, coded in React, has finished loading? The usual javascript tricks, don't seem to work for React, meaning that you cannot use safely these:

document.readyState == 'plete' && jQuery.active == 0

We are working on automated tests and because of this, we cannot have access to client side code, so we cannot or should create callbacks etc, in order to get the info we want. The easy way is to use thread sleep, but this is very unreliable, frustrating, and bad practice. Is there another way, like executing a js script that will return such information?

Is there a way to make sure that a web page, coded in React, has finished loading? The usual javascript tricks, don't seem to work for React, meaning that you cannot use safely these:

document.readyState == 'plete' && jQuery.active == 0

We are working on automated tests and because of this, we cannot have access to client side code, so we cannot or should create callbacks etc, in order to get the info we want. The easy way is to use thread sleep, but this is very unreliable, frustrating, and bad practice. Is there another way, like executing a js script that will return such information?

Share Improve this question edited Apr 19, 2019 at 10:31 gandalf_the_cool asked Apr 18, 2019 at 11:09 gandalf_the_coolgandalf_the_cool 7182 gold badges11 silver badges25 bronze badges 1
  • In which way do you depend on the page to be loaded pletely? – Peter Lehnhardt Commented Apr 18, 2019 at 11:15
Add a ment  | 

2 Answers 2

Reset to default 3

Just in case someone needs this...

The approach below is the best to solve your problem.

function Component() {
    const [loaded, setStatus] = useState(false);

    document.onreadystatechange = () => {
        setStatus(document.readyState === "plete");
    }
    return {loaded ? <Loaded />: <Loading />};
}

Use the new useEffect api coupled with useState can help you achieve what you want,

Something like the following:

Inside your functional ponent:

 function yourComponent() {
   const [isLoading, setLoader] = useState(true)
   useEffect(() => {
     // Here you can access your API to get the Network state instead on document ready
       setLoader(document.readyState == 'plete' && jQuery.active == 0)
   }, [])

   return (
     <div>
       {isLoading && <Loader />}
       {!isLoading && <OtherComponent />}
     </div>
    )}

then you can use isLoading state tu display a Loader in your JSX part and hide it if the readState changes

发布评论

评论列表(0)

  1. 暂无评论