静态脚本标记中的跨浏览器onload事件 [英] Cross-browser onload event in a static script tag

查看:85
本文介绍了静态脚本标记中的跨浏览器onload事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在html文档中,是否存在跨浏览器的方式将onload事件与静态脚本标签相关联?

Is there a cross-browser way to associate an onload event to a static script tag, in a html document?

以下内容在IE 7和IE 8中将不起作用:

The following will not work in IE 7 and IE 8:

<script onload="DoThat" type="text/javascript" src="..."></script>

某些背景

我找到了一种使用动态脚本标记和if语句完成此操作的方法.例如,在此MSDN文章中进行了解释.

I have found a way to accomplish this with a dynamic script tag and if statements. It is for example explained in this MSDN article.

我的问题是我需要找到当前的脚本标签,因为我正在构建将DOM元素就地插入的小部件.过去我已经找到了一些解决方法,但是它们都有缺点.我希望在脚本onload事件上使用"this"关键字会有所帮助.

My issue is that I need to locate the current script tag, because I am building widgets that insert DOM elements in-place. In the past I have found some workarounds to do this, but they all have their downside. I am hoping that using the "this" keyword on a script onload event will help.

推荐答案

据我了解,您需要代码才能知道其属于哪个脚本元素.然后,您将在此脚本旁边插入必要的HTML窗口小部件内容,或者将其附加到脚本父级,等等.如果是这样,那么我将向您提出另一种方法.

As far as I understand, you need your code to know what script element it belongs to. You would then insert necessary HTML widget content right next to this script or append to the script parent, etc. If so then I would propose you another approach.

在小部件javascript文件中,放置下一行代码:

Inside you widget javascript file you place next line of code:

var scripts = document.getElementsByTagName('script'),
    thisScript = scripts[scripts.length - 1];

thisScript是您要查找的DOM元素,此代码位于的当前脚本元素.很简单.

thisScript is the DOM element you are looking for, current script element this code located in. So simple.

为什么有效. 详细说明 http://feather.elektrum.org/book/src.html .只是一个摘要:

Why it works. Detail explanation http://feather.elektrum.org/book/src.html. Just an abstract:

在页面中加载带有src的脚本时,该页面的其余部分尚未编写.这意味着无论页面包含多少个脚本,当前开始执行的都是最后一个

When a script with a src is loaded in a page, the rest of the page is not yet written. The implication is that no matter how many scripts a page contains, the one currently starting to execute is the last one

这是一种非常简单有效的技术,尽管并不是很多人知道这种可能性.它是可靠的,并且100%与浏览器兼容.顺便说一下,Google使用此代码来呈现+1按钮:

This is fairly simple and effective technic, although but not so many people know about this possibility. It's reliable and 100% browser compatible. By the way, Google uses this code to render +1 buttons:

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
  {lang: 'dk'}
</script>

那么,如何思考api脚本如何获取此哈希参数呢?在我的示例中,它是thisScript.innerHTML

So how do think how the api script could get this hash parameters? In my example it would be thisScript.innerHTML

这篇关于静态脚本标记中的跨浏览器onload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆