I have a website that has a lot of popups, whenever a user load a popup (via ajax) there is a JavaScript code also loaded in the popup, I want this JavaScript code to be removed when its popup removed.
Main site code:
<body>
...
<div id="popup" style="display:none">
</div>
...
</body>
and then a loader in js file:
$.ajax('url',{
success:function(data){
$("#popup").show().html(data);
};
});
one of the views that ajax call and push it in the popup:
some html codes
<script>
$(document).on('click',function(){
console.log("document click");
});
</script>
when the user closes the popup, I use this code to empty the popup:
$("#popup").hide().html("");
but this doesn't end the on click event that was loaded, and any functions in the view will still exist in the memory and can be called!
this is an issue because I have a lot of popups here, and JavaScript eats the memory after a while, so I need to refresh the browser after using the website for some time, plus, events are duplicated whenever the popup reloaded!
If it not possible to clear these JS from the memory, are there any workaround for it?
$(document).off('click');?? - (api.jquery.com/off), for the script which is loaded viaajaxgive it anidand use.remove()on the script element, but you'll still need to removeevent handlersscriptanidand remove it as well, thus thefunctions"destroy"everything that was in your dynamic script by setting things toundefinedand so forth, this would have to be done via a cleanup or unload function you called when removing the partial view, perhaps the accepted answer on this post (stackoverflow.com/questions/34997399/…) will get you going.