简体   繁体   English

window.addEventListener('load') 在 PC 上工作正常,但在移动设备上不行

[英]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.我开发了反应网站,它在 PC 上按预期工作,但在移动设备上却没有。

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.我添加了一个功能来在网站第一次加载时设置主题。加载事件会在PC上触发,但不会在移动设备上触发,因为每当我尝试在移动设备中打开我的网站时,它都无法正确加载主题。 Also I checked this by added alert('works') in the themeSet function and yes it execute in Pc but not on mobile .我还通过在themeSet function 中添加 alert('works') 来检查这一点,是的,它在Pc中执行,但在移动设备上不执行。

I am sure that window.addEventListener('load', this.themeSet);我确信window.addEventListener('load', this.themeSet); is not fired on Mobile but works on PC.不会在移动设备上触发,但可以在 PC 上运行。 this is weird I don't know why这很奇怪,我不知道为什么

Note: window.addEventListener('scroll', this.onScroll);注意: 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/这是我用反应创建的网站: https://notse.dev/

You can see it remembers which theme you selected in PC even if you reload.即使重新加载,您也可以看到它会记住您在 PC 中选择的主题。

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.经过一些研究,我发现了一个与我的问题相关的代码,它可以工作,我猜原因是服务器中已经触发了加载事件,即使只有当我从移动设备加载我的网站时才加载 Dom 我不知道确切为什么它适用于 PC 没有错误,但我想这可能是原因。

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')
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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