替换 xhtml+xml 页面中的 document.write()
我在一家编写软件的公司工作,该软件的客户端站点嵌入了 < script language="JavaScript" src=..... 等等。我们很大程度上依赖 document.write 将元素写入页面。我们的一位客户出于某种原因选择使用内容类型“application/xhtml+xml”,这使得 document.write() 在 Chrome 中无法使用。
我明白为什么会这样,并且符合 DOM 的代码应该创建每个元素,设置其属性,如果需要,用文本节点填充它,将文本节点附加到其父级,并将父级附加到某个页面元素......
但是什么是一个不需要所有这些垃圾的好解决方法?其中的 write() 包含如此多的元素,如果我们制作节点并将它们像 Knex 或乐高积木或其他什么东西一样固定在一起,那么生成的代码将非常丑陋。
编辑:尝试使用 CDATA,但即使是这一行也受到与我们的脚本嵌入相同的页面上的 xhtml 解析器的类似谴责:
<script language="text/javascript"><![CDATA[document.write('hi');]]></script>
I work for a company that writes software which client sites embed with < script language="JavaScript" src=..... etc. etc. We depend quite a bit on document.write to write elements out to the page. One of our clients for some reason has opted to use the content-type "application/xhtml+xml", which makes document.write() unusable in chrome.
I understand why this is, and that DOM-compliant code should create each element, set its attributes, fill it with a text node if needed, attach the text node to its parent and the parent to some page element....
but what's a good workaround that doesn't require all this junk? The write()s therein have so many elements that the resulting code would be hideous if we made nodes and fastened them together like Knex or Legos or what-have-you.
edit: Tried using CDATA, but even this line is condemned similarly by the xhtml parser on the same page as our script embed:
<script language="text/javascript"><![CDATA[document.write('hi');]]></script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,您需要将 HTML 修复为有效的 XHTML,但这比将所有代码转换为使用 DOM 操作要少得多。
Note that you'll need to fix the HTML to be valid XHTML, but that should be much less work than converting all the code to use DOM manipulation.
也许您可以创建一个
text/html
类型的 iframe,将内容写入其中,然后将节点导入回主页。Perhaps you can create an iframe of type
text/html
, write the content into that, and then import the nodes back into the main page.我们一直在使用 Jquery 并设置超时来重写与您的类似组织提供给我们的代码。以下是 Search Ignite 中的一个示例:
超时还有一个额外的好处,可以让我们的页面在用户浏览器加载外部代码之前响应用户,如果外部供应商的服务器出现故障,这非常有用。是的,我们丢失了一些跟踪统计数据,但用户体验并没有受到影响。
显然,您将无法依赖 JQuery,但您已经了解了总体思路。
We've been using Jquery and set timeouts to rewrite code supplied to us by similar organisations to yours. Here's an example from Search Ignite:
The timeout has the added benefit of making our page responsive to the user before the the external code has been loaded by the users browser, very useful if the external supplier's servers ever go down. Yes we loose some tracking stats but the user experience is not compromised.
Obviously you won't be able to rely on JQuery but you get the general idea.