HTML and JS to dynamically load, refresh, and execute JavaScript from external file 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.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Sandbox&lt;/title&gt;
        &lt;meta charset="UTF-8"&gt;
        &lt;link rel="stylesheet" href="/JSDev/styles.css"&gt;
    &lt;/head&gt;
    &lt;body onload="document.getElementById('refreshButton').click()"&gt;
        &lt;h1&gt;Sandbox&lt;/h1&gt;
        &lt;!--
            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.
        --&gt;
        &lt;button id="refreshButton" onclick="loadScript('sandbox.js')"&gt;
            Refresh script
        &lt;/button&gt;
        &lt;button id="runButton" onclick="sandbox()"&gt;
            Run script
        &lt;/button&gt;
        &lt;br&gt;
        &lt;button id="refreshRunButton" style="font-weight:bold"
                onclick="document.getElementById('refreshButton').click();
                         sandbox();"&gt;
            Refresh and run script
        &lt;/button&gt;

        &lt;script&gt;
            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);
            }
        &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
This code is very clean, and I believe that it is a very useful tool for any JavaScript developer.



This is not very efficient:

&lt;body onload="document.getElementById('refreshButton').click()"&gt;


Why? Well, think about what your code has to do:


Locate refreshButton.
Wait for refreshButton to load.
Find its onclick method and call it.


Sure, this isn't terribly inefficient, but it can be made simpler.

I see what you are trying to do by not having the HTML code memorize anything; everything is handled in references which all boils down to a few elements.

While this is nice, it would be much more efficient if you called refreshButton's onclick method itself. So, you would just call loadScript:

&lt;body onload="loadScript('sandbox.js')"&gt;




This:

if(js !== null)


Can be reduced to this:

if(js)


I think the way I wrote it is better, because the way I read your code is like this:


  If the functions that JS is loaded with returned null...


And I read what I wrote as:


  If JS exists...


This may just be me, however.

The reason why you can make this change is because, in JavaScript, null is a falsey value and therefore can be treated as though it were false.



Be careful with that runButton button. If the user acts too fast by quickly reloading the script and then trying to run it, there could be some problems; what if the script has not loaded yet?

Rather than silently failing and leaving a non-technically inclined user dumbfounded, it would be better to notify the user of problem (and prevent failing due to an attempt at trying to run a currently non-existent function).

Read this StackOverflow post for some ways you could check if the script has loaded.

In your case, you already have your work laid out for you: the sandbox.js source file creates a global sandbox function that you try to call.

Therefore, you can write this to make sure that the script has loaded:

if(typeof sandbox !== "undefined") {
    sandbox();
} else {
    window.alert("The script has not been loaded yet!");
}




In response to this comment:


  "append the newly-created script element to the head": I'm following
  the JS book I'm studying from (I'm a neophyte at JS and the DOM,
  coming from C++). In fact, JS may not necessarily be best in head.
  (//stackoverflow.com/q/10994335)


This is a different response to that comment.

It doesn't matter where you put the scripts now that the browser has already fully loaded. The browser is not going to stop again and load the code (even if it did, that would be good (referencing to my response comment)).