0

Is it at all possible to enqueue javascript file early on page template file? I want to use this way of including scripts to keep my structure clean (so each page template has its own styling and scripts in it). I don't want to use the conditionals inside functions.php. I don't want to change functions.php. I only want to modify template file. I can enqueue the script no problem, but it is always added at the end of the page, and I need this script to be available upfront (before some of the HTML is displayed - preferrably before ANY of the HTML is displayed).

  • Why would you like to go against an accepted, agreed-upon, maintainable practice of enqueuing from within functions.php? No peer pressure here, just curious. – montrealist Jul 9 '15 at 13:41
  • The reason is exactly as I wrote (please read again). The reason is(quoting myself): I want to use this way of including scripts to keep my structure clean (so each page template has its own styling and scripts in it) – Vladimir Despotovic Jul 9 '15 at 14:01
0

Short Answer: Yes, but...

Just make sure your call to wp enqueue script is before the call to get_header(). The problem is that when you're in a later part of your template the header including the script is already sent to the browser so you can't change it any more.

While this is possible I'd still encourage you to reconsider and put this in the functions.php or a simple plugin. Enqueueing scripts is application logic and therefore shouldn't be in a template.

  • thanks, this works. I tried this but with a cached version, it didn't work. Now it does. And thanks for the enqueueing tip. Looks like this is the proper way to do this (since everyone suggests that). – Vladimir Despotovic Jul 9 '15 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.