比document.onload更快地启动onclick [英] Initiate onclick faster than with document.onload

查看:93
本文介绍了比document.onload更快地启动onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html页面的链接,我想附加一个函数到他们的onclick事件。一种方法是:

 < a href =save.phponclick =save();返回假;的rel = 保存 >保存< / A> 

但我知道这不是最好的做法。所以我等待window.onload,循环链接,并使用rel =save将保存功能附加到链接。这样做的问题是它等待直到整个页面加载完毕,这可以在链接显示和点击后几秒钟。



还有另外一种方法呢?

解决方案

Internet Explorer有一个方便的属性,用于< ;脚本>标记为延迟。这是为了延迟脚本的解析,直到文档完成加载。对于支持它的其他浏览器,您可以像其他人所建议的那样使用DOMContentLoaded,也可以使用不支持的浏览器,您可以退回onload。

 < script type =text / javascriptdefer> 
// - DOM解析完成后运行此代码
< / script>

我做了一个快速的Google搜索DOMContentLoaded延迟,并找到可能有帮助的以下页面: / p>

http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-event-for-browsers


I have html-pages with links where i want to attach a function to their onclick-event. One way to do it is of course:

<a href="save.php" onclick="save(); return false;" rel="save">Save</a>

But I know this is not the best practice. So instead I wait for window.onload, loop through the links and attach the save-function to the links with rel="save". The problem with this is that it waits until the whole page has finished loading which can be several seconds after the link is displayed and clickable.

So is there another way to do this? Avoiding onclick in the html but that makes it work immediately when the link is rendered.

解决方案

Internet Explorer has a handy attribute for <script> tags called defer. It's for delaying the parsing of a script until the document has finished loading. For other browsers that support it, you can use DOMContentLoaded, as someone else suggested and for browsers that don't support either you can fall back to onload.

<script type="text/javascript" defer>
//- Run this code when the DOM parsing has completed
</script>

I did a quick Google search for "DOMContentLoaded defer" and found the following page that might help:

http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-event-for-browsers

这篇关于比document.onload更快地启动onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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