wp_enqueue_script done correctly, now how do I init/call script?

I have added the skrollr script to a wordpress site. I believe it’s done correctly and the script loads correctly/shows in inspector. Here’s the code…

function creationsphere_enqueue_scripts() {

    if (!is_admin()){

        wp_enqueue_script( 'skrollr_js', get_stylesheet_directory_uri() . '/js/skrollr.min.js', array(), NULL, true);

    }
}

add_action( 'wp_enqueue_scripts', 'creationsphere_enqueue_scripts');

I’m using a purchased wordpress theme so I want to keep my own scripts and alterations to a child theme. So I have the script in a ‘js’ folder inside the child theme, and get_stylesheet_directory_uri() points to the child theme.

Read More

So that’s all working but according to the help i’ve been following i now need to call the script (initialise it). The code is…

// Init Skrollr
var s = skrollr.init({
    forceHeight: false
});

The problem is it doesn’t explain where to put this and I don’t know where? I believe it said to add it to another .js file like main.js, but I want to keep everything in the child theme directory.

Could anybody please help me with this? Many thanks!

Related posts

Leave a Reply

1 comment

  1. Few things here:

    • Firstly, always add priority to your action. This prevents that your script gets overridden later by other scripts. Set your priority very low so that your script loads dead last, something like 9999

      add_action( 'wp_enqueue_scripts', 'creationsphere_enqueue_scripts', 9999);
      
    • You don’t need to check for back end or front end. wp_enqueue_scripts only works on the front end. Back end scripts uses the admin_enqueue_scripts hook to load scripts and styles for the back end

    • For the little piece of js, create a js file in your child theme’s js folder and call it whatever you like. Add that code to it and save it. You can now just enqueue it normally

    After all this said and done, your code should look like this

    function creationsphere_enqueue_scripts() {
    
            wp_enqueue_script( 'skrollr_js', get_stylesheet_directory_uri() . '/js/skrollr.min.js', array(), NULL, true);
            wp_enqueue_script( 'NAME FOR HANDLE', get_stylesheet_directory_uri() . '/js/NAME OF JS FILE', array(), NULL, true);
    
    }
    
    add_action( 'wp_enqueue_scripts', 'creationsphere_enqueue_scripts', 9999);