语言重定向与javascript

Language redirection with javascript

本文关键字:javascript 重定向 语言      更新时间:2023-09-26

我必须在Business Catalyst(不是我的选择)中建立一个多语言网站,我唯一的语言切换器和链接rel="alternate"之前的选择是JS。经过大量的试验和错误,我得到了这个工作:

<script type="text/javascript">
document.write("<ul>"); 
document.write("<li><a href='"http://localhost:8888/en/" + location.pathname + "'">English</a></li>");
document.write("<li><a href='"http://localhost:8888/fr/" + location.pathname + "'">French</a></li>");
document.write("<ul>"); 
</script>

唯一的问题是它很慢,而且可能写得很糟糕。是否有更好的方法来编写代码?也许加载速度更快,可能使用jQuery?

事先非常感谢您的帮助

安东尼奥

你可以在你的html中包含以下内容:

<ul id="multilang">
    <li>
        <a href="http://localhost:8888/en/">English</a>
    </li>
    <li>
        <a href="http://localhost:8888/fr/">French</a>
    </li>
</ul>

然后使用jQuery操作url。

$(function () {
    $.each($("#multilang a"), function () {
        $(this).attr('href', $(this).attr('href') + location.pathname);
    });
});

我通常建议避免使用基于字符串的动态html,因为随着时间的推移,它往往难以维护。相反,我建议采用某种基于模板的解决方案。有几个选择,但一个流行的框架是KnockoutJs

http://knockoutjs.com/

1- A一个初学者。document.write将用列表替换整个DOM,因此,我建议将列表附加到html元素。

2-为了提高性能,尽量减少函数调用以减少开销。选项1:准备html并将其写入一个字符串,然后附加该字符串。例如

var lang = "<ul><li>stuff...</li><li>other stuff....</li></ul>";

或者,为了可读性,

lang = "<ul>";
lang = "<li><a href='"http://localhost:8888/en/" + location.pathname + "'">English</a></li>";
lang = "<li><a href='"http://localhost:8888/fr/" + location.pathname + "'">French</a></li>";
lang = "</ul>";
然后

$("#change_lang").html(lang);//change_lang is a div <div id="change_lang"> that you have prepared to put the links inside. 

3-也许你可以从你的服务器直接加载html, 没有JS打印它在屏幕上为你。把它放在。html页面(我不确定你的页面结构,因此,我不知道为什么这种方法可能不适合你)但是直接加载html而不等待JS和JQuery加载将使显示更快。

<ul>
    <li><a href="http://localhost:8888/en/yoursite.html">English</a></li>
    <li><a href="http://localhost:8888/fr/yoursite.html">French</a></li>
</ul>

4-也试着把你的JS代码放在单独的文件中,然后最小化它们以减少大小,从而减少加载时间。将JS放在单独的文件中允许浏览器缓存它们,并消除了每次加载它们的需要。搜索PageSpeed向你展示各种提高网站性能的方法。