Maybe you’re like me and develop your JavaScript with an endless cycle of “edit… save… refresh” to see/test the results. This gets pretty tiring if you’re having to fill in a form or wait for a complicated page to load up each time! I thought, “Why can’t I just save the JavaScript and use it without having to reload the browser window? Can’t it just replace it in memory… live?” Yes, it can. Here’s how to do it.
1. Build the loader function:
Put the following code in the document <head>
<script type="text/javascript">
function LoadMyJs(scriptName) {
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = scriptName;
docHeadObj.appendChild(newScript);
}
</script>
2. Automatically call the loader once the page has loaded
<body onLoad="LoadMyJs()">
3. Place a button on the page to trigger the dynamic reload:
<input type="button" name="reloadjs" value="Reload JavaScript" onClick="LoadMyJs('
my_live_loading_script.js
')">
4. Load your page!
Now once your page is loaded it will called the LoadMyJs() method. This method does the following:
- Defines a function called “LoadMyJs” that takes on parameter which we will herein refer to by the variable “scriptName”
- Get the first (and only, of course) “head” tag as an object using the getElementsByTagName() method built into JavaScript.
- Create a new variable called “
dynamicScript
” as a “script” (the funciton equivalent of having written a <script> tag). - Set the type to “text/javascript” (just the same as the
type="text/javascript"
in the <script> definition). - Tell the browser that the “source” (abbreviated “src”) of the JavaScript is whatever address was passed to the function when it was called (in this example, “
my_live_loading_script.js
“); - Take the now-defined “
dynamicScript
” ojbect and appended it to the document head.
There you have it! Whenever you make changes to your JavaScript file, just click the “Reload JavaScript” button on your page and the browser will reload the JavaScript without you having to reload the page and all that hassle.
From here you may want to get creative, just and loading multiple scripts or even using a couple functions to toggle between the effects of two different script (e.g., one that gives helpful info to newbies and another that gives more advanced help message).
Finally, a special thanks to Patrick Hunlock for his “How to Dynamically Insert JavaScript And CSS” article that gave me the head start on this!