Gerald Hughes
Gerald Hughes

Reputation: 6159

Adding script dynamically to <head> in Angular

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?

Upvotes: 1

Views: 6710

Answers (4)

Shy Agam
Shy Agam

Reputation: 1415

If you can allow yourself to install a new library, use the HeadService that comes with @bespunky/angular-zen. It provides a safe and strongly-typed access to the head element.

Your component / service would look something like this:

 import { Component, OnInit } from '@angular/core';
 import { HeadService       } from '@bespunky/angular-zen/core';

 @Component({
     selector   : 'zen-head-service-demo',
     templateUrl: './head-service-demo.component.html',
     styleUrls  : ['./head-service-demo.component.css']
 })
 export class HeadServiceDemoComponent implements OnInit
 {
     constructor(private head: HeadService) { }

     ngOnInit()
     {
         this.head.addElement('script', /* config object or config function */);
     }
 }

Live examples | Service docs | Service API

🙋‍♂️ Remember to npm install @bespunky/angular-zen and import CoreModule from the /core package.


TLDR

💡 The HeadService has other cool features like looking up elements by attributes, support for well known elements (e.g. scripts and styles), etc.

💡 It's also testing-ready, meaning you can easily mock the document element or spy on it.

Upvotes: 1

griFlo
griFlo

Reputation: 2164

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);
}

Upvotes: 7

Codemaker2015
Codemaker2015

Reputation: 1

You can simply get the reference of an element using getElementByTagName() method by passing the tag name. After that you have to create a script variable then insert code to the variable using innerHTML attribute. Finally insert the script variable into head.

Try the following code,

  const head = document.getElementsByTagName('head')[0];
  const script = document.createElement('script');
  script.innerHTML = 'your code';
  head.insertBefore(script, head.firstChild);

Upvotes: 1

Marco Bertelli
Marco Bertelli

Reputation: 425

here my example that i actually use in my project :

<head>
    <div *ngIf="dati">
        <title>{{dati.data.field_meta_tag.description}}</title>
    </div>
</head>

for do this you need to use rjxs operator and take the response to your api,in my example i use it only for the title now but you can use it for all.

Upvotes: -6

Related Questions