Google 的 +1 按钮:他们是如何做到的?
在探索 Google 的 +1 按钮时,我发现他们提供的代码有两点奇怪:
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{lang: 'en-GB'}
</script>
<g:plusone size="tall" href="http://www.google.com"></g:plusone>
所以我有两个问题:
第一: Google 如何使用 script
标记之间的文本?
第二: 语法
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
元素在 DOM 中完全可见:
Google 的狡猾伎俩是将内容放入具有外部
src
的中>。在这种情况下,
src
会覆盖块内的内容并执行外部脚本,但元素的内容仍然可以通过 DOM 读取,即使他们什么也不做。
不。如果他们为 HTML+plusone 创建了自己的文档类型,那么它可能是有效的,但它不满足 HTML 的有效性,而且在 XHTML 文档中它甚至不是命名空间格式良好的,除非您也为其添加额外的
xmlns:g
。<script>
elements are perfectly visible in the DOM:Google's sneaky trick is to put content in a
<script>
that has an externalsrc
. In this case thesrc
overrides the content inside the block and executes the external script instead, but the contents of the<script>
element are still readable through the DOM even though they do nothing.No. If they made their own doctype for HTML+plusone it could be valid that, but it doesn't satisfy validity for HTML, and it isn't even namespace-well-formed in an XHTML document, unless you add an extra
xmlns:g
for it too.不
无效的伪命名空间
No
Invalid psuedo-namespaces
第一个技巧很有趣。它看起来像是一种将“全局”参数从页面标记传递到外部脚本的创造性方法。有方法来查找获取当前正在运行的代码的
元素,如果该
元素的内部文本可以从 DOM 访问,即使浏览器忽略它,我也不会感到惊讶。
在您的问题中,此模式允许每个外部客户端脚本(至少)使用自己的本地化设置,并且还允许服务器端代码渲染该参数作为渲染
第二个技巧,我不太确定。基本上,我认为大多数浏览器都会将命名空间
元素视为未知甚至无效,因此它们应该 渲染其内容,但当然它不会执行任何操作,因为该元素一开始就是空的。但是,客户端代码可能仍然能够使用 DOM 导航来匹配命名空间元素,并将其替换为自己生成的内容。
The first trick is interesting. It looks like a creative way to pass "global" arguments from the page markup to external scripts. There are ways to find the
<script>
element that sources the code that's currently running, and I would not be surprised if the inner text of that<script>
element was accessible from the DOM even though the browser ignores it.In your question, this pattern allows each external client-side script to use (at least) its own localization settings, and also allows server-side code to render that parameter as a side effect of rendering the
<script>
element itself. That's impressive.The second trick, I'm not so sure about. Basically, I think most browsers would consider the namespaced
<g:plusone>
element as unknown or even invalid, so they should render its content, but it won't do anything, of course, since that element is empty to begin with.However, client-side code might still be able to match the namespaced element using DOM navigation, and replace it with its own generated content.