简体   繁体   中英

window.addEventListener('load') works fine on PC but not on mobile

I have developed react website which works as expected on PC but not on Mobile.

componentDidMount() {
    window.addEventListener('scroll', this.onScroll); // this fire works fine
    window.addEventListener('load', this.themeSet); // this event does not fired in Mobile
 }

I added a feature to set theme when the site load for the first time.The load event fires on PC but not on mobile coz whenever i try to open my website in mobile it does not load the theme correctly. Also I checked this by added alert('works') in the themeSet function and yes it execute in Pc but not on mobile .

I am sure that window.addEventListener('load', this.themeSet); is not fired on Mobile but works on PC. this is weird I don't know why

Note: window.addEventListener('scroll', this.onScroll); works completely okay on both devices laptop and mobile.

I hope i'll get an answer Thank you in Advance.

Here is site I created with react: https://notse.dev/

You can see it remembers which theme you selected in PC even if you reload.

But on Mobile when you reload it just reset to dark theme.

After Some research I found a code related to my problem and it works i guess the reason would be that load event is already fired in server even though the Dom did not load only when i load my site from a mobile I don't know exactly why it works for PC without eror but yeah i guess this could be the reason.

The code that works for mobile is this:

if (document.readyState === "complete") {
      this.themeSet()
      console.log('readySate')
    } else {
      window.addEventListener('load', this.themeSet);
      console.log('event here')
    }

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