【问题标题】:When using document.write to load a different css stylesheet, browser refreshes infinitely使用 document.write 加载不同的 css 样式表时,浏览器无限刷新
【发布时间】:2012-12-09 22:14:55
【问题描述】:

我试图在我的 wordpress 博客上使用两种不同的样式表,这样当通过 Web 访问页面时使用一个样式表,当通过我们的 iOS 应用程序访问博客内容时使用另一个样式表。现在我们将 ?app=true 附加到来自我们 iOS 应用程序的 URL 请求,希望在我们的博客中我们可以搜索这个字符串并加载不同的样式表。我们正在使用 JSON API 插件,以便我们的 iOS 应用程序可以通过编程方式拉取我们的博客文章并在 iOS 应用程序的 Web 视图中显示它们。

在我的 wordpress 博客中,我使用了在 URL 中查找 ?app=true 的 javascript,如果是,则加载不同的样式表。

<script language="javascript" type="text/javascript">
    var location = window.location.href;
if(location.indexOf("?app=true") > -1) {        
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"appstyle.css\" />");
}
</script>

此代码位于我的 wordpress 主题的 header.php 文件中的标签内。

我尝试使用的样式表名为 appstyle.css,与 header.php 位于同一目录中。

我遇到的问题是,使用此代码会无限重新加载浏览器页面。问题似乎出在 document.write 函数上,因为没有该网页可以正常加载(尽管它显然没有加载 appstyle.css 样式表)。

我也试过这个 if 语句:

if(window.location.search.indexOf('?app=true') === 0) 

但好像没什么区别。

是否有更好的方法来加载不同的样式表,具体取决于它是在 iOS 应用程序中加载还是在 Web 中加载?我的代码有什么地方做错了吗?

【问题讨论】:

标签: javascript ios css wordpress stylesheet


【解决方案1】:

尝试:

location === window.location

在控制台中。

它将输出true。这表明全局变量location 已经设置并指向window 的当前location 对象。使用您的代码,您通过分配一个新值来更改该变量,这会触发浏览器重新加载。

要修复它,只需为变量使用另一个名称,例如:

var currentLocation = window.location.href;

或者将您的代码放在一个自执行函数中,以将其与全局范围分开:

(function (){
  var location = window.location.href;
  if(location.indexOf('?app=true') > -1) {        
    document.write('<link rel="stylesheet" type="text/css" href="appstyle.css" />');
  }
}());

【讨论】:

  • 谢谢 - 更改为“var currentLocation = window.location.href;”修复了浏览器刷新问题。然而,实际上并不是在阅读 appstyle.css 样式表。我也没有看到它在页面源代码中创建 html。我只能在html中看到原始样式表 ""
  • 传递的 url 是 localhost:8888/?app=true 或单个帖子:localhost:8888/?p=29?app=true
  • 我已将您的问题标记为正确,因为您修复了浏览器刷新问题。我在这里为新问题(未加载 appstyle.css 样式表)创建了一个新问题:stackoverflow.com/questions/14007048/… -- 非常感谢您的帮助!
【解决方案2】:

如果您坚持使用 document.write,请记住在加载或稍后调用 document.close()。

【讨论】:

  • 我会用什么来代替 document.write?
【解决方案3】:

此行有语法错误:

document.write("<link rel="stylesheet" type="text/css" href="appstyle.css" />");

尝试将其更改为:

document.write('<link rel="stylesheet" type="text/css" href="appstyle.css" />');

或者做适当的转义

document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"appstyle.css\" />");

【讨论】:

  • 抱歉 - 我粘贴了错误的文本行。我用这一行进行了正确的转义 document.write("");但我仍然有问题
猜你喜欢
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2014-06-21
  • 2014-02-06
  • 2014-12-18
  • 2019-05-31
相关资源
最近更新 更多