简体   繁体   中英

Javascript style.display sometimes doesn't work

I am creating my first PWA (progressive web app). It has been a long and painful learning process but I think I'm nearly there. My one remaining problem is not (I think) directly related to the PWA but is just a javascript issue.

I am using a standard piece of code downloaded from an online example:

// Register service worker to control making site work offline

if('serviceWorker' in navigator) {
  navigator.serviceWorker
           .register('sw.js')
}

// Code to handle install prompt on desktop

let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Update UI to notify the user they can add to home screen
  addBtn.style.display = 'block';

  addBtn.addEventListener('click', (e) => {
    // hide our user interface that shows our A2HS button
    addBtn.style.display = 'none';
    // Show the prompt
    deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice.then((choiceResult) => {
        deferredPrompt = null;
      });
  });
});

Note that there are three instances of style.display. The first will hide the add-button if it's not required. The second shows the add-button when it is required. The third should hide the button after it has been clicked to place the app on the home screen. However the button remains on-screen until the screen is refreshed.

In an effort to debug it, I changed the line to

addBtn.style.color = 'red'

That worked, so the text on the button turned red after it was clicked.

No doubt it's something simple and obvious (it usually is), but for the life of me I can't see it. Any suggestions would be appreciated.

Can you try maybe adding a class with display: none; and display: block; and just toggle it?

I haven't really identified the problem, but I have found a work-around. I have added a

location.reload();

after the button has been clicked. That has masked, if not solved, it.

In passing, I would also add that the caching which is a fundamental part of PWAs is a nightmare for development. I found I was having to rename the above javascript file every time I changed it, otherwise the main page would find the cached version instead of the new one.

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