Tom
Tom

Reputation: 33

jQuery Load Script Once onClick

I am trying to load 2 scripts in jquery only once a #element is clicked. Currently, I am trying to use:

    jQuery("#element").click(function () {
       jQuery('#elementcontainer').load('/js/jquery.script.js');
       jQuery('#elementcontainer').load('/js/jquery.script2.js');
    });

The problem is that the scripts load everytime the #element is clicked. I only want the scripts to load once - and currently they also make like this

"http://127.0.0.1/pck/Js/jquery.script.js?_=1279101767931"

How can I load the scripts ONLY once and stop the non-cache. I am using ASP.NET MVC ?

Thx

Upvotes: 3

Views: 6246

Answers (2)

Nick Craver
Nick Craver

Reputation: 630637

You can use one() like this:

jQuery("#element").one('click', function () {
   jQuery('#elementcontainer').load('/js/jquery.script.js?' + (new Date().getTime()));
   jQuery('#elementcontainer').load('/js/jquery.script2.js?"' + (new Date().getTime()));
});

.one() executes the event handler exactly once, the Date() piece is for the cache. I'm no sure you want .load() though, if your intent is just to get/execute the scripts, then $.getScript() is more appropriate, like this:

jQuery("#element").one('click', function () {
   jQuery.getScript('/js/jquery.script.js');
   jQuery.getScript('/js/jquery.script2.js');
});

$.ajax() requests of dataType = "script" (which $.getScript() is) won't be cached.


If you want to cache, you have two options, you can use $.ajaxSetup() once (but this affects all subsequent $.ajax() or shorthand calls):

$.ajaxSetup({ cache: false });

Or make the full $.ajax() call version that $.getScript() is short for:

jQuery("#element").one('click', function () {
   jQuery.ajax({ url: '/js/jquery.script.js', dataType: 'json', cache: true });
   jQuery.ajax({ url: '/js/jquery.script2.js', dataType: 'json', cache: true });
});

Upvotes: 9

Bogdan Constantinescu
Bogdan Constantinescu

Reputation: 5356

This will do the trick:

  jQuery("#element").click(function () {
       jQuery('#elementcontainer').load('/js/jquery.script.js');
       jQuery('#elementcontainer').load('/js/jquery.script2.js');
       jQuery(this).unbind('click');
    });

Note the unbind() method called on $(this) (which is the element #element). You can check more unbind() functionality here.

Upvotes: 0

Related Questions