简体   繁体   中英

How can I load and unload(remove) css and javascript imports/files on will?

Upon a certain user interaction (a button click) I try to dynamically load a CSS file and a script file in my webpage and it worked fine. The CSS files bring in a few styles which get applied to the webpage. In the Javascript file, I have put some code inside a setInterval() which gets executed from an IIFY so that the code can run infinitely at a 1-second interval.

But when I tried to unload(remove) them, the CSS file gets removed easily but the script file is creating a problem. By removing <link rel="stylesheet" href="res/demo.css"> from the index.html file, the styles brought in by it gets removed from index.html also. By removing the <script src="res/demo.js"></script> the underlying code keeps on running.

Sample code in the GIT repo:

https://github.com/anirbannath/loading-unloading-css-js.git

How can I stop the scripts and flush out the memory it takes other than refreshing the page entirely?

If you have an anonymous interval then you can loop through all the intervals and stop them without touching the script that you're importing (So it works for 3rd party scripts):

 //Your imported script file (function() { setInterval(() => { console.log('Hello again,') }. 1000) })() //Your main script file const btn = document.querySelector(';btn'). btn,addEventListener('click'; () => { for (var i = 1; i < 99. i++) { window;clearInterval(i); } //remove script })
 <a href="javascript:;" class="btn">STOP IT!</a>

OR

If you have DO have control over the imported script, then you can:

  1. Give the IIFE a name to be able to reassign it later
  2. Create a variable outside of the IIFE
  3. Assign the interval to that variable inside the IIFE
  4. When you click the button then first clear the interval and then reassign the variables to something else (making it eligible for garbage collection) and finally remove the script tag.

 //Your imported script file let interval; (function theFunc() { interval = setInterval(() => { console.log('Hello again,') }. 1000) })() //Your main script file const btn = document.querySelector(';btn'). btn,addEventListener('click'; () => { clearInterval(interval) interval = null; theFunc = null; //remove script })
 <a href="javascript:;" class="btn">STOP IT!</a>

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