• Hi
    There have already been a few questions somewhat related to this topic, but none of them seems to be really answered. Plus there all outdated/closed.

    The question: Is there a WordPress friendly way to load script and styles asynchronously per JavaScript?
    My problem isn’t how to do this in general but how to deal with it in WordPress since WordPress loves to have all styles/scripts registered/enqued.

    Usage examples: Scott Jehl and the guys Filament Group have many savvy techniques how load CSS, scripts and fonts for better perceived page performance but they all rely on having scripts/styles inline in the <head> and loading additional scripts/styles from there.

    Also Google’s page speed insights proposes to inline the above-the-fold css and load the rest of the styles via a script after pageload. But even this doesn’t seem WordPress conform.

    Any suggestions how to go about this are much appreciated!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator James Huff

    (@macmanx)

    Personally, I don’t think there’s any right or wrong way, just whatever works and what you’re most comfortable with.

    I like to store any JS included with the theme in a /js/ directory under the theme, because it might as well be with the theme if the theme is including it, and that’s what all of the WordPress default themes have done the past few years.

    Then, reference it in <head> like this:

    <script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/example.js"></script>

    In the above, it’s fetching the directory for the currently active theme (which means it’s independent of whichever domain you’re using, and independent of HTTP vs. HTTPS) then pulling example.js out of the /js/ directory in the theme’s directory, where the js is located at /wp-content/themes/[current-theme]/js/example.js

    Thread Starter lorenzp

    (@lorenzp)

    Hi James, thank you for your answer.

    So you suggest to not enque the styles or scripts at all with wp_enqueue_script / wp_enqueue_style? Doesn’t that cause potential problem spots for working with third-party plugins?

    Thanks in advans for your (or anyones) response!

    Moderator James Huff

    (@macmanx)

    No, that doesn’t cause any conflicts with plugins. As long as you use the same theme, the script will be there.

    If it’s a theme-specific script, I haven’t really found any reason to _enqueue it rather than just including it in the header.php template.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘WordPress friendly way to load script/styles via JS?’ is closed to new replies.