Support » Themes and Templates » What is the correct way to reference Javascript?

  • Resolved RenzoGamboa


    I am currently using WP 3.5 and created a child theme from the twetytwelve theme. I have been using wp_head() to put the scripts in the <head> section of my child theme. the functions look something like this:

    function carrousel_script(){
    	echo '<script type="text/javascript" src="'.get_template_directory_uri().'/js/jquery.jcarousel.pack.js"></script>';
    add_action('wp_head', 'carrousel_script');

    I know there is a better way to do this and I’d like to know it. The codex talks about wp_enqueue_script(‘custom-script’) – I am a little confused there. Also, notice I am just using jquery scripts so nothing custom, nothing fancy. Thanks in advance for the help!!..
    my site: Visual Upload

Viewing 3 replies - 1 through 3 (of 3 total)
  • Using wp_enqueue_script() is really the best way to do this.

    Using your code above as an example, you could use something like this:

    function add_js () {
        wp_enqueue_script ("carousel_script", get_template_directory_uri().'/js/jquery.jcarousel.pack.js", array ("jquery"));
    add_action ("wp_enqueue_scripts", "add_js");

    What this does is add in your script, labeling it as ‘carousel_script’ ans setting it up to require jQuery.

    I’d also suggest using the $in_footer argument of wp_enqueue_script to make the js script load into the wp_footer() hook.

    Too many or large scripts loading into the head may slow down page loading times. Check out his in the codex for more information:

    Thank you guys so much for your help!! that has cleared up all my doubts!!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘What is the correct way to reference Javascript?’ is closed to new replies.