Material Box

Material Box

WEB Design & Material Images

JavaScript - Avoid variable declaration errors when loading the same script multiple times

JavaScript

A method and simple code example to avoid variable and function declaration errors when needing to load the same script multiple times without reloading the page in JavaScript.


In HML, we have placed the target elements.

<div id="target">Target element</div>
<script id="test-js">let target = document.querySelector('#target');</script>

Even if you delete the JavaScript code from the HTML using remove(), variable and function names declared in the deleted code cannot be newly declared and will cause errors.

If you don't edit the script contents and declarations, to avoid duplicate declaration errors when reloading, write the JavaScript that gets reloaded as an immediately invoked function expression (IIFE).
In the code example below, the <script> tag gets deleted then readded to the body element, but using an IIFE avoids duplicate variable declaration errors.

// Delete loaded <script> from DOM
document.querySelector('#test-js').remove();

// Create JavaScript with same variable name declared in deleted script
let script = document.createElement('script');
// Write script contents as IIFE
script.innerHTML = `(function() {let target = document.querySelector('#target');})();`;
script.id = 'test-js';
document.body.appendChild(script);

JavaScript - Avoid variable declaration errors when loading the same script multiple times

TitleJavaScript - Avoid variable declaration errors when loading the same script multiple times

CategoryJavaScript

Created

Update

AuthorYousuke.U