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
  • 593
  • 6
  • 9
  • 19

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
  • 597
  • 3
  • 25
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
  • 180,066
  • 36
  • 283
  • 292
  • 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