Are there any drawbacks when setting the HTML lang attribute dynamically on the client side?
Asked Answered
K

4

7

We are currently serving the initial index page for a single page application without the lang attribute set on the HTML tag. At the moment we are also not setting it dynamically after the page is loaded.

Are there any problems with screen readers if the language is set dynamically instead of already setting it on the initial page?

Kazbek answered 8/3, 2017 at 10:14 Comment(2)
Just one thing to keep in mind: AFAIK search engines might look at the lang attribute in order to serve their users content that fits their language setting. So it could have some negative effect on SEO. Not sure though.Particia
Re search engines: They might do all kinds of things, but there is no evidence of any of them actually paying attention to lang attributes. Google has explicitly said they ignore it, partly because it is so often wrong, partly because they can infer the language from the content.Micaelamicah
B
4

Modern screenreaders understand javascript and use the javascript modified DOM instead of the initial DOM.

As long as you do not change the lang attribute too late (after the screenreader already started to speak), it should work.

Note that switching language might result in some bugs if you do not also change the current URL using the HTML5 api history.

Barracuda answered 8/3, 2017 at 11:43 Comment(0)
B
0

No, not to my knowledge. We have done it already in a published product. Our case was getting the wished language for Spell-Check in contenteditables. So we dynamically change the lang attribute of all elements and it just works fine.

Bigham answered 8/3, 2017 at 10:21 Comment(0)
H
0

No. The previous two answers have it, but I am linking a CodePen demo that I use for clients / talks just so you can test and confirm it for yourself:

http://codepen.io/aardrian/pen/eBOrZY

I toggle the main, but I have also done it on the html and you can tweak the following code in the pen to do so:

function toggleLang(l) {
  var m = document.querySelector('main');
  m.setAttribute('lang', l);
}
Heiduc answered 8/3, 2017 at 15:52 Comment(0)
H
0

There is one very serious flaw:

Browsers that have automatic translation (chrome, edge), cannot detect language changes. When using the translation feature, they will always try to translate from the language set at the beginning of the page.

Hebert answered 12/6, 2023 at 5:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.