Is there a way to push javascript or css ‘on-page’ in a template via functions.php

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x