[英]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.在某个用户交互(单击按钮)后,我尝试在我的网页中动态加载 CSS 文件和脚本文件,它运行良好。 The CSS files bring in a few styles which get applied to the webpage.
CSS 文件引入了一些应用于网页的 styles。 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.
在 Javascript 文件中,我将一些代码放在从 IIFY 执行的setInterval()中,以便代码可以以 1 秒的间隔无限运行。
But when I tried to unload(remove) them, the CSS file gets removed easily but the script file is creating a problem.但是当我尝试卸载(删除)它们时,CSS 文件很容易被删除,但脚本文件正在产生问题。 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.通过从 index.html 文件中删除
<link rel="stylesheet" href="res/demo.css">
,由此引入的 styles 也会从 index.ZFC35FDC70D5FC69D269883A822C7A53 中删除。 By removing the <script src="res/demo.js"></script>
the underlying code keeps on running.通过删除
<script src="res/demo.js"></script>
底层代码继续运行。
Sample code in the GIT repo: GIT repo 中的示例代码:
https://github.com/anirbannath/loading-unloading-css-js.git 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?除了完全刷新页面之外,如何停止脚本并清除 memory?
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):如果您有一个匿名间隔,那么您可以遍历所有间隔并停止它们,而无需接触您正在导入的脚本(因此它适用于 3rd 方脚本):
//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:如果您可以控制导入的脚本,那么您可以:
//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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.