[英]How can I load and unload(remove) css and javascript imports/files on will?
在某個用戶交互(單擊按鈕)后,我嘗試在我的網頁中動態加載 CSS 文件和腳本文件,它運行良好。 CSS 文件引入了一些應用於網頁的 styles。 在 Javascript 文件中,我將一些代碼放在從 IIFY 執行的setInterval()中,以便代碼可以以 1 秒的間隔無限運行。
但是當我嘗試卸載(刪除)它們時,CSS 文件很容易被刪除,但腳本文件正在產生問題。 通過從 index.html 文件中刪除<link rel="stylesheet" href="res/demo.css">
,由此引入的 styles 也會從 index.ZFC35FDC70D5FC69D269883A822C7A53 中刪除。 通過刪除<script src="res/demo.js"></script>
底層代碼繼續運行。
GIT repo 中的示例代碼:
https://github.com/anirbannath/loading-unloading-css-js.git
除了完全刷新頁面之外,如何停止腳本並清除 memory?
如果您有一個匿名間隔,那么您可以遍歷所有間隔並停止它們,而無需接觸您正在導入的腳本(因此它適用於 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>
或者
如果您可以控制導入的腳本,那么您可以:
//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.