Search code examples
javascriptgoogle-tag-manager

Add Link Rel tags in a script via custom HTML tag in Google Tag Manager


I want to add link tags in a script and place this in the head section of the site as mentioned below:

<link rel="preconnect" href="https://cdn.abc.com/" crossorigin />
<link rel="dns-prefetch" href="https://cdn.def.com/" />
<link rel="preconnect" href="https://sdk-02.fhi.com/" crossorigin />
<link rel="dns-prefetch" href="https://sdk-02.ret.com/" />;

I am using Google Tag Manager and I am pushing this script through Custom HTML Tag.

<script>  
  (function() {
    var s = document.createElement('script');
    s.innerHTML =
'<link rel="preconnect" href="https://cdn.abc.com/" crossorigin />'
'<link rel="dns-prefetch" href="https://cdn.def.com/" />'
'<link rel="preconnect" href="https://sdk-02.fhi.com/" crossorigin />'
'<link rel="dns-prefetch" href="https://sdk-02.ret.com/" />';
    document.head.appendChild(s);
  })();

</script>

The issue is when I check the source code, I only see the first link added. The remaining links are not added.


Solution

  • To Put Link Tags in the Script you can put it in a loop.

    (function() {
        var a = [
        '<link rel="preconnect" href="https://cdn.abc.com/" crossorigin />',
            '<link rel="dns-prefetch" href="https://cdn.def.com/" />',
            '<link rel="preconnect" href="https://sdk-02.fhi.com/" crossorigin />',
            '<link rel="dns-prefetch" href="https://sdk-02.ret.com/" />',
        ]
        var s = document.createElement('script');
        for(var i = 0; i < a.length; i++){
            s.innerHTML += a[i]
        }
        document.head.appendChild(s);
      })();
    

    If you want add dynamicly links to the head tag you can use following code

    (function() { 
     var linkNames = [ 
     {"url":"https://cdn.abc.com/", "rel":"preconnect", "crossorigin":true},
     {"url":"https://cdn.def.com/", "rel":"dns-prefetch", "crossorigin":false},
     {"url":"https://sdk-02.fhi.com/", "rel":"preconnect", "crossorigin":true},
     {"url":"https://sdk-02.ret.com/", "rel":"dns-prefetch", "crossorigin":false},
     ];
     for(var i = 0; i < linkNames.length; i++){
         var link = document.createElement('link'); 
         link.rel = linkNames[i].rel;
         link.href = linkNames[i].url;
         if(linkNames[i].crossorigin == true){
             link.crossOrigin = true;
         } 
         document.head.appendChild(link); 
     }
    
     })();