Socialify

Folder ..

Viewing page-loader.js
61 lines (54 loc) • 1.8 KB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// This script is used to load the appropriate local page content for the current page.

const getLocaleLanguge = () => {
    if (navigator.languages && navigator.languages.length) {
      return navigator.languages[0].split('-')[0];
    } else {
      return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
    }
}

const isLocaleLoaded = (cl) => {
  for (const language of languages) {
    if (cl.includes(language)) {
      return true;
    }
  }
  return false;
}

const lang = getLocaleLanguge();
const languages = []
const languagesDiv = document.querySelector('.languages') ? document.querySelector('.languages').getElementsByTagName('a') : [];
const page = window.location.pathname;

for (let i = 0; i < languagesDiv.length; i++) {
    const language = languagesDiv[i].getAttribute('data-lang');
    languages.push(language);
}

const a = document.querySelectorAll('a');
for (let i = 0; i < a.length; i++) {
    let split = page.split('/');
    // Remove empty strings from the array.
    split = split.filter(Boolean);
    if (a[i].getAttribute('data-lang')) {
        const currentLanguage = a[i].getAttribute('data-lang');
        let baseLink = "";
        for (const element in split) {
            baseLink += "/" + split[element];
            if (languages.includes(split[element])) {
                baseLink = baseLink.replace(split[element], currentLanguage);
            }
        }
        a[i].href = baseLink;
    } else {
      const href = a[i].getAttribute('href');
      let baseLink = "/";
      for (const element in split) {
        baseLink += split[element] + "/";
        if (languages.includes(split[element])) {
          break;
        }
      }
      a[i].setAttribute('href',href.replace('/<l>/', baseLink));
    }
}

if (!isLocaleLoaded(page)) {
    window.location.href = page + lang;
}