The following code is designed to load and refresh JavaScript code from an external file sandbox.js
and allow it to be refreshed dynamically and executed without reloading the entire page. The sandbox.js
file is assumed to contain a function sandbox()
which may contain arbitrary JavaScript code. As the title within the code below suggests, it's a sandbox intended for rapid testing of JavaScript code, where I can just save code in the IDE and execute the updated code immediately.
The most current version of this code is available here.
<!DOCTYPE html>
<html>
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="/JSDev/styles.css">
</head>
<body onload="document.getElementById('refreshButton').click()">
<h1>Sandbox</h1>
<!--
Change the parameter in the loadScript() call below to load
JavaScript from another file. The code is designed to avoid
repetition of the file name elsewhere in the code by having other
buttons programmatically trigger this button.
-->
<button id="refreshButton" onclick="loadScript('sandbox.js')">
Refresh script
</button>
<button id="runButton" onclick="sandbox()">
Run script
</button>
<br>
<button id="refreshRunButton" style="font-weight:bold"
onclick="document.getElementById('refreshButton').click();
sandbox();">
Refresh and run script
</button>
<script>
function loadScript(location) {
// Check for existing script element and delete it if it exists
var js = document.getElementById("sandboxScript");
if(js !== null) {
document.body.removeChild(js);
console.info("---------- Script refreshed ----------");
}
// Create new script element and load a script into it
js = document.createElement("script");
js.src = location;
js.id = "sandboxScript";
document.body.appendChild(js);
}
</script>
</body>
</html>