From my reading it seems there is a good case for loading scripts like jquery and dependencies into the footer as a preference if possible; however 2 things confuse me which. Firstly the default for wp_enqueue_script() is to put the script in the footer and second (and possibly related) there is a line from the codex
Note that you have to enqueue your script before wp_head is run, even if it will be placed in the footer.
Is this to say that even if the script is set to load into the footer it still loads early on and so we loose several of the advantages of footer placement?
Edit – Just in case the above incorrect statement confuses anyone in future. I realised since that I’d been reading the codex wrong and that the default for wp_enqueue_script()
is NOT to put the script in the footer
There is a lot of leftovers in script-related articles in Codex that are not entirely correct (putting it mildly).
The enqueue should not be done before
wp_head()
, it should be done onwp_enqueue_scripts
. Which is technically early insidewp_head()
.It doesn’t harm performance, because registering/enqueueing script is merely explaining to WordPress how it should be done. Actual script output is done as separate print action.
See my answer in where is the right place to register/enqueue scripts & styles for more detailed description of how things work.
Typically, it’s smarter to put scripts at the bottom to make the page load faster. But this also depends on how you’re using the scripts and what the code is doing. If you try to use jQuery in an inline script (i.e.
<script></script>
) tag in the body of the page without hooking on to the document’s ready event, things will break.Remember, the library needs to be loaded before you try to use it.
No. You enqueue your script and specify that it will be loaded in the footer. WordPress will look at it, remember for later, and actually write the script when it gets to the
wp_footer()
tag. All of your scripts should be enqueued with thewp_enqueue_scripts
action regardless of where you want them actually printed to the page.