Search code examples
javascripthtmldomappendhead

Appending a script to <head> doesn't work, but writing it manually does? Chrome debugger renders them the same


Why doesn't this work? I know the question is frowned upon, but in my case, I just can't seem to get why appending this script into head doesn't work the way I want it to.

It appends the script, I'm able to see it in the chrome debugger. But I still get the error

tools.js:26 Uncaught ReferenceError: script_object is not defined

which doesn't make sense, because if I copy/paste the outerHTML directly from the chrome debugger (the one that was created by my script and appended to head), and paste it directly into my index.htm. Then it works just fine.

Code:

var afterTools = document.getElementById("toolsId").nextSibling;
var script = document.createElement("script");
script.setAttribute("type","text/javascript");
script.setAttribute("src","scripts/thescript.js");

document.head.insertBefore(script, afterTools);


let temp = script_object;  // Object hardcoded in thescript.js
console.log(temp);

The script I'm appending after:

  <script id="toolsId" type="text/javascript" src="scripts/tools.js" defer></script>

What it boils down to is that chrome's debugger shows no difference between manually writing the script in, or appending it. Yet it doesn't recognise the object within the script unless it's manually written.


Solution

  • tools.js:26 Uncaught ReferenceError: script_object is not defined
    

    You are referencing a variable before it is instantiated. It must be available BEFORE referencing it, probably caused by the fact that you are using defer..

    defer

    This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. The defer attribute should only be used on external scripts.

    source: https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/script

    So the browser is only executing it after your first code that depends on it, hence it is not available at that moment.