add javascript files only when plugin is called?

I’m writing a WP plugin that might be called on any page using a simple function call:getDeck(Deck_id) – and i’d like to add my javascript files on pages where this function is called ONLY, as opposed to having it on every page…

What do I do?

Related posts

Leave a Reply

2 comments

  1. If your scripts can be printed in the footer add the enqueue to the definition of getDeck, with the final argument set to true.

    I.e in your plugin file

    function getDeck( $deckId )
    {
        wp_enqueue_script( $handle, $src, $deps, $ver, true );
    
        //do other stuff
    }
    
  2. I’m writing a WP plugin that might be called on any page

    The issue here is that you want to be able to call the function on any page. And if you’re distributing the plugin, you will either require users to add code or you should provide a settings page on which the user can choose on which page the file should load.

    If you’re developing the plugin for one specific website and you want to add the JS to specific pages, you can do so with is_page():

    function my_scripts_method() {
        if( is_page( 'page-name' ) ){
           wp_enqueue_script( /* params */ );
        }
    }
    
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );