Question: have an interesting conundrum. I need to load about 8 javascript files and the same number of styles for my plugin. These are only needed where ever my shortcode is ran.

I've tried to load them with print\_styles and print\_scripts but they aren't rendering properly, plus to do so breaks xhtml validation. So at the moment they load on every page and due to the number of files needed its not feasible to leave it like this. 

On another project I wrote a function into my plugin's index.php file that would take the current page, search it for my shortcode and if found only then would it print the scripts, but this is an ugly hack.

Has anybody got any suggestions or solutions?
any help would be appreciated,
regards,
Daithi

Answer: 
to answer my own question... I had it write the first time. You have to search each page to check that your shortcode is being used. This has to be done when page data is loaded and before page is displayed. To me it is complete overkill on the system, but unfortunately it is the way it is. I got this information from:
[get\_shortcode\_regex](http://codex.wordpress.org/Function_Reference/get_shortcode_regex)
and
[old nabble](http://old.nabble.com/Re:-checking-if-post-has-shortcode,-before-header-is-%09output--p26058406.html)

So first:

```
add_action('template_redirect','wp_my_shortcode_head');

```

then:

```
function wp_my_shortcode_head(){
  global $posts;
  $pattern = get_shortcode_regex(); 
  preg_match('/'.$pattern.'/s', $posts[0]->post_content, $matches); 
  if (is_array($matches) && $matches[2] == 'YOURSHORTCODE') { 
        //shortcode is being used 
  }
}

```

replace 'YOURSHORTCODE' with the name of your shortcode and add your wp\_enqueue\_scripts into where it says //shortcode is being used.
Just read this tutorial over here: <http://scribu.net/wordpress/optimal-script-loading.html>

Seems to be the best way.

```
add_action('init', 'register_my_script');
add_action('wp_footer', 'print_my_script');

function register_my_script() {
    wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
}

function print_my_script() {
    global $add_my_script;

    if ( ! $add_my_script )
        return;

    wp_print_scripts('my-script');
}

```

> 
> In this case, the script will be enqueued only if the $add\_my\_script
>  global was set at some point during the rendering of the page.
> 
> 
> 

```
add_shortcode('myshortcode', 'my_shortcode_handler');

function my_shortcode_handler($atts) {
    global $add_my_script;

    $add_my_script = true;

    // actual shortcode handling here
}

```

> 
> So, the script will be added if [myshortcode ...] was found in any of
>  the posts on the current page.
> 
> 
>