1

I have a questions about JQuery's .one() API, I'm trying to load some functions only once after the document has been fully loaded using .one() API and this doesn't seem to work and I can't figure out why...

can I please get some help?

$(document).one('load',function(){
// Perform something here...
});
lukieleetronic
  • 623
  • 7
  • 10
  • 23
  • 1
    Shouldn't `$(window).load(function(){ foo(); bar(); });` do what you need? Your functions `foo(); bar();` will run only once. Count on that! – Roko C. Buljan Dec 28 '14 at 12:56
  • Oh my god, this works like a charm.. what's the difference between this and doing something like $(document).ready(function(){/.../})? they both achieve the same thing right? I was having a problem where the function inside .ready() executes every time any AJAX call is made within the document.. – lukieleetronic Dec 28 '14 at 13:01
  • Sounds like your AJAX isn't AJAX! – Roamer-1888 Dec 28 '14 at 13:03
  • http://stackoverflow.com/questions/5182016/what-is-the-difference-between-window-load-and-document-ready – Roko C. Buljan Dec 28 '14 at 13:05

2 Answers2

3

This works use instead of "load" to "ready" not sure why its not working with the load

$(document).one('ready',function(){
    // Perform something here...
    alert("ther you go");
});

Keep in mind that "ready" fires before "load".

Naveen Setty
  • 615
  • 5
  • 26
2

Makes no sense to use .one() in any of the combination document ready or window load.

api.jquery.com/one:

Attach a handler to an event for the elements. The handler is executed at most once per element per event type

you clearly don't expect the ready or load to trigger twice. Those run once per session so it's quite silly to use .one() for this (artificial) events.

Also it's good to know that:

$(document).one("ready", function(){
  console.log("DOCUMENT SILLY ONE READY");
});

$(function(){ // (DOM ready shorthand)
  console.log("DOCUMENT READY");  // not only will this one run...
});    
              // but also this is the order result:

                    // DOCUMENT READY
                    // DOCUMENT SILLY ONE READY

so to conclude, you only need

$(function(){
  // DOM is ready to be manipulated
  foo();      
  bar();
});

or:

$(window).load(function(){
  // DOM, metadata, scripts, files, styles, images...etc are load and ready
  foo();      
  bar();        
});

and your functions will not run more than once.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Because `ready` doesn't override each other, if you're using AJAX, the same function may be called on multiple page visits. – JediBurrell Sep 27 '17 at 07:58