Below is an example of a problem I am having. I am using $(locator).html(data) to replace a DIV after an ajax call. The issue is that the DIV also have a SCRIPT tag inside it, and those functions in that SCRIPT tag are remaining in memory after I .empty() that DIV.
Is there a way to remove/de-register/undefine all functions in the SCRIPT tag automatically/programmatically? I guess I thought the Jquery .empty() would do that, but I guess not. I think I could do something manual like test1 = undefined but I don't want to have to explicitly do that for all the functions.
Thanks.
EDIT: I am working on a legacy product, so there are dozens of html files with dozens of functions that could be loaded for the newString variable. So my goal is not to change any of those, but to solve this lingering-function issue at the time of .empty() and .html() when replacing the div contents.
EDIT 2: And I can't just "delete" the function, because I don't always know what the function(s) will be. I need to do this programmatically. (seems I keep getting flagged as a duplicate question, but again, I can't delete what I don't know yet)
function change () {
// this newString is mock html data coming back from an ajax call
let newString = "<p>Reloaded page</p>";
console.log("#emptyme HTML before empty():")
console.log($("#emptyme").html());
$("#emptyme").empty();
console.log("#emptyme HTML AFTER empty():")
console.log($("#emptyme").html());
$("#emptyme").html(newString);
if (typeof test1 !== "undefined") {
$("#error").html("test1() WAS STILL FOUND!!");
console.log("test1() WAS STILL FOUND!! Function definition from memory is:");
console.log(test1);
}
console.log("finished change function.");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="emptyme">
<p>
Initial page
</p>
<script>
function test1 () {
console.log("this is test1 function.");
}
</script>
</div>
<button onclick="change()">
load change
</button>
<div id="error">
</div>
</body>
</html>