[Fixed] Adding script dynamically to <head> in Angular

Issue

I’ve checked some example that demonstrate how to add script with URL dynamically in Angular

But I want to add this kind of stuff to <head>

<script>
  !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
  n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
  document,'script','https://connect.facebook.net/en_US/fbevents.js');

  fbq('init', '<FB_PIXEL_ID>');
  fbq('track', "PageView");
</script>
  
  

or

  <noscript>something</noscript>
      

or both.

Any ideas, examples?

Solution

You can make an function, which gets the (first) head tag from the document and add an created script tag (with the code you specify in innerHTML) before the first child of the head tag:

export function addScriptsToHead() {
  const head = document.getElementsByTagName('head')[0];

   
  const script = document.createElement('script');
  script.innerHTML = 'your code';

  head.insertBefore(script, head.firstChild);
}

Leave a Reply

(*) Required, Your email will not be published