开发者

Can using element.focus() just after an element's declaration in HTML be harmful?

I want to make a form in which I want to automatically give focus to a field. In the old days I learned to always wait doing any DOM manipulation till window.onload has fired, as the DOM might not be ready. Since JQuery the DOMContentReady event has grown famous, which fires (in compliant browsers) somewhat earlier than window.onload.

That still gives a delay between the moment the field is shown and the moment it gets focus (by using document.getElementById("inputfield").focus() in window.onload or after DOMContentReady has been triggered). To minimize that delay, some people suggest using focus() directly after the element in your page, like:

<form name="f">
  <input id="q" autofocus>
  <script>
    if (!("autofocus" in document.开发者_开发百科createElement("input"))) {
      document.getElementById("q").focus();
    }
  </script>
  <input type="submit" value="Go">
</form>

(Example from Dive Into HTML5)

Also, the Google Closure team advices this practice: "the preferred way is to use inline scripts as soon as possible", like another answer on SO states.

I don't want to debate whether this is bad practice or not (in general, I agree with the opinion that content and behaviour should be separated, preferably in separate files). My question is: can this be harmful? For instances, causing error messages in some browsers because the field might still not have been rendered properly (and don't forget mobile browsers). Any advice is appreciated.


No, it is not harmful and it is the (subjective) best way to do it.

Reasons it is the best:

  • Code executes as soon as successfully possible (instead of waiting for whole DOM, it waits until it reaches a certain element)
  • Does not rely on DOM events (which still have yet to be standardized)

Reasons it sucks:

  • Lack of behavioral separation
  • Difficult to maintain because code will be scattered all over the place
  • Increased overall page size due to existense of several <script> tags


To be honest, I'd have thought that if you are seeing a delay between the page popping up and the element getting the focus, then that does suggest that your page might just be too large, so reducing that would be your first port of call. I know that I'd be very unhappy if I saw inline code like that. As Josh says, it would be a maintainability nightmare.

However, on the question of it being harmful, I'd have thought that if the browser has processed the script node to run the javascript, then it will also have processed the input node, so it should be available to the code. Therefore I wouldn't expect an error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜