I have this code to submit a form automatically on page load, but it takes like 20 seconds in order to do the submit after the page is completely loaded.
Am I doing anything wrong here?
If not, how to bypass that 20 seconds delay?
Can we make the body onload
event faster?
The code:
<html>
<body onload="document.forms['loginform'].submit();">
<form id="loginform" name="loginform" action="https://login.url.com" method="post" style="visibility:hidden">
<input type="hidden" value="" name="hhh">
<input type="text" value="username" id="login_field" name="username">
<input type="password" value="pass" id="passw开发者_运维知识库ord_field" name="password">
<input type="hidden" value="" id="password_strength" name="password_strength">
<input type="hidden" value="/index.php" id="sendto" name="sendto">
<button id="btn_logon" type="submit"><span>Login</span></button>
</form>
</body>
</html>
The load event is fired after all dependencies of the page - images, externa resources, etc. have been loaded. The event you should watch for is the one that gets fired when the DOM is ready - DOMContentLoaded
which has been standardized in HTML5.
For a cross-browser solution, pick an implementation from any of the existing JavaScript libraries like MooTools, jQuery, Dojo, etc.
This link contains one implementation. If your DOM content is too big, and downloading and parsing just that is taking time, then consider adding your script right after the <form>
itself.
<form id="loginform" name="loginform" action=".." method="post">
...
</form>
<script>
// submits the form right after it is parsed
document.forms['loginform'].submit();
</script>
As Anurag mentioned, the DOMContentLoaded
event would be better as it "doesn't wait for other things like images, subframes, and async scripts to finish loading" (MDN).
To implement this in your code, you should remove the onload
attribute from the <body>
tag and instead use this code:
<script>
addEventListener("DOMContentLoaded", () => document.forms['loginform'].submit());
</script>
Or, better yet, grab the form by its id:
<script>
addEventListener("DOMContentLoaded", () => document.getElementById("loginform").submit());
</script>
精彩评论