How to get javascript function to execute only once on dom ready

I get a hi warning again and again, how can I get him to do this once and stop:

function doSomething() {
   alert('hi');
}

$(function() {
    doSomething();
});
+6
source share
7 answers
        // Fired once when document is ready
        $(document).one('ready', function () {
              doSomething();
        });

Using .one ensures that this is done only once, and not repeatedly. It is possible to host multiple document.ready event listeners (if you need other events to run multiple times) if you are not overdoing it for readability.

.one is especially useful when you want a warning to appear when you first open a web page or when you install a mobile application for the first time.

+8
source

, JS HTML. HTML.


:

$(function(){
});

. . , :

function($){
    // $ always refers to jQuery here
    ...        

}(jQuery);
// $ might not be defined here in compatibility mode.
+3

:

window.onload = function() {
    doSomething();
}
+1

... cookie - :

$(document).ready(function () {
    if ($.cookie("blocker") == 1) {
        //your code or without code;
        return;
    } else {
        //your code for first time
        $.cookie("blocker", 1, {
            expires: 1 / 24 / 60 //time, this is one minut
        });
    }
}); 

,

+1

, ...

, - :

var doSomething = function() {
  alert('hi');
}

$(document).ready(function () {
  doSomething();
});
0

- ?

$(document).ready(function() {
    doSomething();
});
0

, :

function doSomething() {
   alert('hi');
}

$(document).ready(function() {
    doSomething();
});
0

All Articles