I'm trying to load an external JavaScript, do some work with it, delete it and load it back again. But I'm having problems and maybe someone can help me understand why.
Here is an example of an external script to be loaded:
class ClassA {
constructor() {
console.log("ClassA object created");
}
}
Here is an example of what I'm trying to do with it:
let aScript = document.createElement("script");
aScript.onload = function() {
//test ClassA object
let classA = new ClassA(); //OK (ClassA object created)
classA = null //OK
//remove/delete the script
document.head.removeChild(aScript); //OK
delete ClassA; //OK
ClassA = null; //OK
window.ClassA = null //OK
//Try to reload the same script...
aScript = document.createElement("script");
aScript.src = "ClassA.js";
document.head.appendChild(aScript);
//...throws error: (ClassA.js:1 Uncaught SyntaxError: Identifier
//'ClassA' has already been declared at VM1088 ClassA.js:1)
};
aScript.src = "ClassA.js"; //loading the script for the first time.
document.head.appendChild(aScript);
Although I'm removing/deleting the script, the class object (ClassA) is still referenced in memory.
Uncaught SyntaxError: Identifier 'ClassA' has already been declared
Is it possible to remove a es6 class from memory? What am I doing wrong?
Thanks.
EDIT
The solutions for the script to be loaded:
window.ClassA = class {
constructor() {
console.log("ClassA object created");
}
}
or
(function(window) {
class ClassA {
constructor() {
console.log("ClassA object created");
}
}
}(window))
this way the same script/class can be load, delete and loaded again. See traktor53 post for further information.
window.ClassA = null;
– Barmar Jan 29 '18 at 20:44