Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - function is defined but never used

I am having trouble reloading the page. I tried to use JavaScript in Vue by adding this code

<body onload="myFunction()">

function myFunction() {
   window.location.reload()
}

This error is poppng up:

 74:10  error  'myFunction' is defined but never used  no-unused-vars

Any suggestions?

question from:https://stackoverflow.com/questions/65713479/function-is-defined-but-never-used

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

no-unused-vars is a ESLint warning. It occurs because you don't call your function anywhere in your javascript code, and ESLint cannot read that it is being called from an HTML attribute.

You can turn off this warning like this:

<script>
/* eslint-disable no-unused-vars */
function myFunction() {
  window.location.reload()
}
/* eslint-enable no-unused-vars */
</script>

Although calling javascript functions from HTML attributes is not good practice today.

There is a javascript way to wait for the load event, instead of using onload attribute:

<script>
function myFunction() {
  window.location.reload()
}

document.addEventListener('DOMContentLoaded', myFunction);
</script>

Regarding the comment on the page reload only once. You can keep the fact that the page has been reloaded in the localStorage:

<script>
function myFunction() {
  // Check that the page has not been reloaded
  if (localStorage.getItem('reloaded') === null) {
    // Save the fact that we are reloading the page, and reload page
    localStorage.setItem('reloaded', true);
    window.location.reload();
  } else {
    // Otherwise, reset the flag so that on the fresh load the page can be reloaded again
    localStorage.removeItem('reloaded');
  }
}

document.addEventListener('DOMContentLoaded', myFunction);
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...