Append a script to the body using JavaScript

Let's assume that you want to append the following script using JavaScript:

javascript
console.log('Erik has the same amount of hair as Bezos, but just a little bit fewer money 💸')

Imagine that you want to append the previous script if it doesn't exist in the DOM:

javascript
let script = document.getElementById('erik') || document.createElement('script')

script.id   = 'erik'
script.type = 'application/javascript'
script.text = `console.log('Erik has the same amount of hair as Bezos, but just a little bit fewer money 💸')`

if(!document.getElementById('erik'))
    document.body.append(script)

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.