WordPress.org

Forums

[resolved] What is the correct way to reference Javascript? (4 posts)

  1. RenzoGamboa
    Member
    Posted 2 years ago #

    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

  2. michael.mariart
    Member
    Posted 2 years ago #

    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.

  3. martinjharvey
    Member
    Posted 2 years ago #

    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:
    http://codex.wordpress.org/Function_Reference/wp_enqueue_script

  4. RenzoGamboa
    Member
    Posted 2 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic