Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djD-REK/c242a0136310bb9a65e1554e4f4480a0 to your computer and use it in GitHub Desktop.
Save djD-REK/c242a0136310bb9a65e1554e4f4480a0 to your computer and use it in GitHub Desktop.
const script = document.createElement("script")
script.type = "text/javascript"
script.src = "script.js"
document.head.appendChild(script)
eval(script)
@likev
Copy link

likev commented Jan 8, 2021

there is no need to use eval(script)
instead you should use

const script = document.createElement("script")
script.src = "script.js"
script.onload = function(){
    //do something
}
document.head.appendChild(script)

or

const script = document.createElement("script")
script.src = "script.js"
script.async = false
document.head.appendChild(script)

@DoctorDerek
Copy link

Thanks for the correction @likev!

You're absolutely right, eval() or Function() are totally optional unless you need to import the script as a string -- or for example are loading the text <script src="..."> and need to evaluate that statement.

I updated the article:
https://levelup.gitconnected.com/how-to-load-external-javascript-files-from-the-browser-console-8eb97f7db778

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment