posicionamiento jquery / JS

I'm going to confess I don't know what's best.

Normally, I place the jquery library in the head of a webpage. I do the same thing for any jquery plugins or javascript functions.

What I'm curious about is where to place the selectors. At the bottom, before the end body tag. Or before the site code.

Ejemplo:

<div id="somediv">stuff inside</div>
<script language="javascript" type="text/javascript">
$(function (){ 

  $("#somediv").hide();

});
</script>

As you can see I place the selector below the html. I've seen it both ways, but I'm curious if there's a best way. And would that also be true for all javascript related functions and plugins.

The reason I as is because sometimes IE complains about placement. While other browsers seem more forgiving, or don't care.

preguntado el 08 de enero de 11 a las 19:01

3 Respuestas

If you place your selectors inside:

$(function() {
     // my DOM selection
});

...then it won't matter since that is a shortcut for a call to jQuery's .ready() Método which ensures that the DOM elements are loaded before the code inside runs.

If your code is positioned Si lo envía después the elements, then you can do without .ready().

Another option is to place your code in a window.onload handler. The downside to this is that it will need to wait for all content, including images, to load before it runs. Probably not what is desired.

Respondido el 08 de enero de 11 a las 22:01

Either way works if you have it inside a document.ready handler, like you already have with $(function (){ ... });. Sin the wrapper, you tener to place it after the elements, e.g. at the end of the <body>.

In either case, be sure the <script> block occurs Si lo envía después jQuery (and any plugins that code needs) are included.

Respondido el 08 de enero de 11 a las 22:01

Both will work fine but if your page becomes complex it may seem to load slowly and appear sluggish; so if variable scoping isn't a problem you may consider placing scripts at the bottom of your pages, which would mean importing jQuery followed by firing off the rest of your scripts within $(function() { })

Respondido el 08 de enero de 11 a las 22:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.