1

What I mean is - when I 'enqueue_scripts' in functions to load CSS or JS into a template it adds the full path.

What I'd like to do is to actually publish the Javascript onto the actual page so it is pushed within like this on the page:

<script> the javascript is printed ON the page NOT a Full Path </script>

I know that there is a plugin for this but I wondering if there is an easier 'functions.php' way of doing this...

Said another way - I am trying to SPEED UP the website, i.e. I am trying to place CSS and JavaScript on the page. Google recommends to "Eliminate render-blocking JavaScript and CSS in above-the-fold content"

That is what I am trying to achieve...

Thanks!

4
  • I fail to understand what is it that you are asking. what is the "this" you are talking about? if you need JS, just add it to your template, what is the problem you are facing? Aug 10 '17 at 2:46
  • I mean - is there a way to print the Javascript directly on the page rather than the full path URL
    – Henry
    Aug 10 '17 at 2:47
  • you are just repeating the question instead of clarifying it :( Aug 10 '17 at 2:48
  • cool, now it is easier to understand what you mean Aug 10 '17 at 2:55
2

You can just hook into wp_head for CSS or JS, or wp_footer for JS (style tags need to be in the header):

function wpse_276403_output_scripts() {
    ?>
    <script>alert('Hello world!');</script>
    <style>
        body {
            background: #F00;
        }
    </style>
    <?php
}
add_action( 'wp_head', 'wpse_276403_output_scripts' );

function wpse_276403_output_scripts() {
    ?>
    <script>alert('Hello world!');</script>
    <?php
}
add_action( 'wp_footer', 'wpse_276403_output_scripts' );

If your script or style depends on a registered or enqueued script, you can use wp_add_inline_style() or wp_add_inline_script() to ensure that the JS/CSS is output after the script or style it depends on:

function wpse_276403_output_scripts() {
    wp_enqueue_script( 'my-dependency-script', '/uri/to/script/file.js' );
    wp_add_inline_script( 'my-dependency-script', 'alert("Hello world!");' );
    wp_enqueue_style( 'my-dependency-style', '/uri/to/stkle/file.css' );
    wp_add_inline_style( 'my-dependency-style', 'body { background: #F00; }' );
}
add_action( 'wp_enqueue_scripts', 'wpse_276403_inline_scripts' );

This way the scripts and styles will only be output if my-dependency-script/my-dependency-style have been loaded, and will load after them. Note that you don't need to add the <script></script> or <style></style> tags.

1
  • v interesting...thanks for that. That works really well for what I am trying to do - I'll try it out.
    – Henry
    Aug 10 '17 at 2:59

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.