noz70629
noz70629

Reputation: 33

run fetched script only once

With the following code:

<a href="#" onmouseover="$.getScript('http://www.example.com/x.js')">aaa</a>

i want to only run x.js one time, what in jQuery can i use to make it execute x.js only one time?

thanks.

Upvotes: 1

Views: 730

Answers (1)

Dave
Dave

Reputation: 10924

The best option would be to attach your event handler through .one() instead:

HTML:

<a id="example" href="#">aaa</a>

JavaScript:

$("#example").one("mouseover", function() {
  $.getScript('http://www.example.com/x.js');
});

Alternatively, if you have to use the inline scripts, you could set a flag and only call $.getScript() the first time (this is not recommended):

HTML:

<a id="example" href="#" onmouseover="doMouseOver();">aaa</a>

JavaScript:

var scriptRan = false;
function doMouseOver() {
  if (!scriptRan) {
    scriptRan = true;
    $.getScript('http://www.example.com/x.js');
  }
}

Upvotes: 1

Related Questions