-3

How we run JavaScript code when page refresh but function still run. I want to run this JavaScript code

<script>
function abc(){

}
</script>
  • 2
    Just follow it with `abc();` (or move the code inside, outside the function). If you put that in a page it will run every time the page is loaded or refreshed. – Reinstate Monica Cellio Feb 06 '18 at 11:05
  • `abc` does nothing, so why run it? – sdgfsdh Feb 06 '18 at 11:05
  • `` – ADyson Feb 06 '18 at 11:06
  • 1
    The question is clear, what happens to a currently executing function, when the user refreshes the page... – Legends Feb 06 '18 at 11:07
  • Can you clear up your question? At the moment it is likely to be closed for being unclear. – evolutionxbox Feb 06 '18 at 11:08
  • 3
    If you're talking about what happens to a function which is running when the page gets refreshed, then simply it stops running. The page which was loaded before the refresh, which was its execution environment, no longer exists, so it stops. Simple as that really. – ADyson Feb 06 '18 at 11:08
  • do you want to know how to get this method running on page load or what happens with `actually` running code after reloading? – messerbill Feb 06 '18 at 11:09

2 Answers2

1

You can get function called/executed on page load or refresh.

function abc(){
// enter your code
}

With JQuery:

$(function(){
  abc();
});

jQuery using .ready() method:

$(document).ready(function() {
   abc();
});

With Normal JS

(function(){
  abc();
})();

function abc(){
      console.log(Date.now())
    }

    $(function(){
      abc();
    });

    $(document).ready(function() {
      abc();
    });

    (function(){
      abc();
    })();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
messerbill
  • 5,499
  • 1
  • 27
  • 38
Abhiii
  • 34
  • 2
  • these functions after refresh will end – umdeveloper Feb 06 '18 at 11:24
  • `these functions after refresh will end ` just like each other function.....javascript will not be executed longer than your page is active....this answer is an upvote worth (in contrast to your question) – messerbill Feb 06 '18 at 11:28
0

You can use ServiceWorkers to be able to run things in background (after refresh, when offline, or when your browser/tab is closed).

scazzy
  • 950
  • 2
  • 8
  • 20