简体   繁体   中英

How to import and exclude a JavaScript code dynamically?

I know my request is very specific, but I am working on a project where I need to import a JavaScript code using a JavaScript file and then exclude it. An example will be more meaningful than an explanation:

// Import code
let script = document.createElement('script');
    script.id = 'newScript'
    script.innerHTML = "class system { static test() { console.log('Hello World !'); } }";
document.body.appendChild(script);
// Call the function of the imported code
system.test(); // Return "Hello World !" in console
// Exclude code
document.body.removeChild(script);
// Call the function of the imported code. Is supposed to make an error because the code is excluded.
system.test(); // Return "Hello World !" in console

I wish the system.test() function was no longer available after excluding the file, but it still works.

Thank you in advance for your help!

You cannot unload js once loaded but you can overwrite object. system=undefined;

 // Import code let script = document.createElement('script'); script.id = 'newScript' script.innerHTML = "class system { static test() { console.log('Hello World;'); } }". document.body;appendChild(script). // Call the function of the imported code system;test(). // Return "Hello World." in console // Exclude code document;body;removeChild(script). system=undefined. // Call the function of the imported code. Is supposed to make an error because the code is excluded; system.test(); // Return "Hello World !" in console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM