Initiate onclick faster than with document.onload

十年热恋 提交于 2019-12-06 04:05:09

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

In your case, you can just leave that as it is. Stick to the simplest possible thing, even if it is not the general best practice.

You could try DOMContentLoaded event instead of load. IE also gives you the defer attribute for script tags, which defers execution until the DOM is loaded. If those don't work for you, then you are stuck with the solutions you mention, as far as I know.

I don't know if this is appropriate for your solution, but you could insert script immediately below the are with the links you need altered. This script would not be wrapped in a function, allowing the browser to execute it immediately when seen. The effect is that you can run script before the full page is loaded, altering only the items that exist above the script being run. (If you reference something below the script, it will fail.)

BTW, this is almost certainly not a best practice, and some would probably label it a worst practice.

How about this?

<a href="javascript:void(save());">Save</a>

Note: This solution requires to users to have Javascript enabled. Not exactly best practice, but may be suitable for your scenario.

The ideal here would be to use the ideas of Unobtrusive Javascript.

In this way, if the Javascript isn't loaded the link would still do something. It's a link right, so it leads the user to another piece of content? - this should work without Javascript. And if the functionality attached to the links can ONLY work with Javascript you should create and insert them into the DOM with Javascript (they aren't clickable if they aren't there...).

(Otherwise how about delegating the click event to a wrapper element? Does that work before the element is complete?)

edit: Oh, and "save" sounds very much like it ought to be a button in a form rather than a link. The Unobtrusive JS stuff still applies though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!