2

I used the following code to redirect all the HTTP pages of a site to the https:// version.

<link rel="canonical" href="">
<script>
    var url = window.location.href; // get current URL
    var link = document.querySelector('link[rel=canonical]'); // get the link element
    var changedUrl = [url.slice(0, 4), 's', url.slice(4)].join(''); // change the URL to https://
    link.setAttribute('href', changedUrl); // set href attribute of link element
</script>

Now my questions is, will Google read the dynamically generated canonical tags and index them like normal canonical tags? Or will I have to try another approach?

3
  • Google does not like if you do different things with JavaScript on or off. Why don't you redirect http visitors to https with htaccess? – Robert hue Aug 10 '16 at 6:45
  • I don't want to redirect the visitors. I just want to add the link rel="canonical" tag in each page. The site is big so I'm looking for a script script that I can place in the website header that will add the tag automatically. – asamolion Aug 10 '16 at 6:49
  • 1
    Sadly, Google will not care what you want. – Simon Hayter Aug 10 '16 at 8:48
1

yes. but it depends. from how fast you insert it. i tested some lazy load scenarios with js and realized, that in google's cache are afterloads visible, which happens even after 5 seconds after onLoad is fired. btw, you will not be able to see it in the search console with fetch as google - fetch as google is only a kind of preview. i know cases, where even not the whole page was shown in fetch as google, because it was too long:)

but don't stretch google's patience - try to make loadtime as fast you can - in reality you never know, how long it will wait. and all tests we can perform have a kind of pretty limited validity, because we don't know, what factors, beside of those we control, are in this game.

if i were you, i would insert canonicals into the header with x-robots-tag - it can be done dynamically, and the tag is already inserted, if google reads the page.

Not the answer you're looking for? Browse other questions tagged or ask your own question.