Support » Fixing WordPress » How to safely include scripts later in a theme

  • Hi All,

    I’ve been reading the documentation about the wp_enqueue_script and wp_register_script functions and it looks to me that according to it, there is no way to safely enqueue a script later in a theme, apart of printing it directly into the footer.

    So, here is one example of what I need – I have a blog page with many posts where a post may or may not need one specific script. My code will know whether the script is needed for the page after the loop in the page. However, according to the documentation the wp_enqueue_script function must be called in the “wp_enqueue_scripts” hook or as explained in the wp_register_script function documentation, before wp_head() is called. This is too early for my code to know whether the script is needed or not and at this point the only safe solution that I can see is just printing the script in the footer, which is not really a good practice.
    Also, I know that currently I can still use the wp_enqueue_script later in the theme, but I’m afraid that this may change in a later version of WordPress and I really want to make sure I follow the docs.

    If anyone can provide any suggestion about what would be the safest way to include the scripts at a later stage, I will be really grateful!
    Thank you

Viewing 1 replies (of 1 total)
  • For anyone interested, I found this article:

    however I’m not really sure if it is a good idea to change the global $wp_scripts variable and whether it will be future versions compatible. At this point I ended up with enqueueing the scripts on some pages that they may not be needed, just to keep the general enqueueing organization same everywhere, but that’s not really good.

    I really can’t believe that there isn’t another way to do this – if anyone else knows another way – please share 🙂

Viewing 1 replies (of 1 total)
  • The topic ‘How to safely include scripts later in a theme’ is closed to new replies.