www.webdeveloper.com
Results 1 to 3 of 3

Thread: Changing canonical

  1. #1
    Join Date
    Apr 2013
    Posts
    1

    Changing canonical

    Hi all,

    I want to add a canonical to a page that is gerated with my CMS.

    For instance, I want to add: <link rel="canonical" href="testURL" /> to my page.

    I figured that this possibele using Javascript and tried the following:

    <head>
    ...
    <script type="text/javascript">
    var head = document.getElementsByTagName('head')[0];
    var canonical = document.createElement('link');
    canonical.setAttribute('rel','canonical');
    canonical.setAttribute('href','testurl');
    head.appendChild(canonical);
    </script>
    ...
    </head>

    Question: Why doesn't this work?

    I am not experienced in programming in Javascript, but I have some basic skills.

  2. #2
    Join Date
    Jan 2010
    Posts
    79
    Hi bud

    Your script is working fine, just because you can’t see it doesn’t mean that it isn’t there.
    Code:
    <script type="text/javascript">
    
    var head = document.getElementsByTagName('head')[0]; 
    var canonical = document.createElement('link'); 
    canonical.setAttribute('rel','canonical');
    canonical.setAttribute('href','testurl');
    head.appendChild(canonical);
    
    alert(head.childNodes[head.childNodes.length-1].rel)
    </script>
    That said I am a bit confused as to why you would want to do this! Most bots spiders crawlers (whatever you want to call them) do not run javascript, that said the googlebot is rumoured to run scripts and make ajax calls but google itself is rather tight lipped on the subject, but some webmasters have noticed javascript errors in the server logs inferring that the googlebot is running some scripts

    Surely your easiest workaround is to just use the canonical link in the way it was intended.
    Code:
    <link rel="canonical" href="testURL" />

  3. #3
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    static meta like that must by pfysically present in the html server, adding it in js won't do anything because it's only used when the page loads.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles