开发者

jQuery Load Script Once onClick

开发者 https://www.devze.com 2023-01-07 07:15 出处:网络
I am trying to load 2 scripts in jquery only once a #element is clicked. Currently, I am trying to use:

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 wan开发者_StackOverflowt 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


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 });
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消