JavaScript
Dynamically inject JavaScript

by Benny Neugebauer

injectScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.async = true;
    script.type = 'text/javascript';
    script.onerror = (event) => (reject(event));
    script.onload = (event) => (resolve(event));
    script.src = url;
    document.head.appendChild(script);
  });
}

injectScript('//www.bennyn.de/alert.js');

injectScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.async = true;
    script.type = 'text/javascript';
    script.onerror = (event) => (reject(event));
    script.onload = (event) => (resolve(event));
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  });
}

injectScript('//www.bennyn.de/alert.js');

They're exactly the same; enter document.head===document.getElementsByTagName("head")[0]

into your Javascript console.

Foxatron

Sign in to comment!