0

In my functions.php file I am loading a particular js script on only the page it is required, as I don't want to load it unnecessarily on pages that don't require it.

function tabs_enqueue() {
    if(is_page( 205 )) {
        wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true);
    }
}
add_action('wp_enqueue_scripts', 'tabs_enqueue');

After testing, this works 100% but my problem is that I don't know where to put the actual jquery on the page that I want it. I can't put it into the footer because then I get errors on the other pages because it is trying to run the code without the js file being loaded. I want to place the code just before the closing body tag. If I put this after the get_footer() code then it is right at the bottom of the source code and if I put it before the get_footer() then it is called before I even load the js files. So, how would I get this code to display just before the closing body tag?

 <script>
    jQuery(window).load(function() {
        //code here

    });
</script>
2

You don't need to add it on a template, you can use the wp_add_inline_script() function. It'd be something like:

function tabs_enqueue() {
    if(is_page( 205 )) {
        wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true);
        wp_add_inline_script( 'ui',
            'jQuery(window).load(function() {
                //code here
            });' );
    }
}
add_action('wp_enqueue_scripts', 'tabs_enqueue');

Hope it helps!

| improve this answer | |
1

While Felipe Elia's answer works, it's better to separate your code. You don't want to have to update your PHP file to change Javascript.

I would add a reference to your javascript file within your page check and be sure to include 'ui' in your required array so your new script won't load until after 'ui' is loaded.

wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/myScript.js', ['ui']);

Then create a file (js/myScript.js) that holds your custom Javascript. I recommend putting your code in a closure so it doesn't get affected by any other scripts.

(function($, window, document){
    // Use strict mode to reduce development errors.
    "use strict";

    // Put your code here.

})(jQuery, window, document);
| improve this answer | |

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.