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