HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

HTML and JS to dynamically load, refresh, and execute JavaScript from external file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filedynamicallyjavascriptrefreshloadandexternalfromhtmlexecute

Problem

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.




Sandbox




Sandbox


Refresh script


Run script




Refresh and run 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);
}



Solution

This code is very clean, and I believe that it is a very useful tool for any JavaScript developer.

This is not very efficient:



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:



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)).

Code Snippets

<body onload="document.getElementById('refreshButton').click()">
<body onload="loadScript('sandbox.js')">
if(js !== null)
if(typeof sandbox !== "undefined") {
    sandbox();
} else {
    window.alert("The script has not been loaded yet!");
}

Context

StackExchange Code Review Q#97629, answer score: 5

Revisions (0)

No revisions yet.