Proper Javascript Implementation

If I interpret the question correctly you:

  • Don’t have any .js javascript files
  • Output any javascript you have from an .php file (presumably code)
  • Include this javascript on the bottom of the page by including the .php file.

So you are actually doing:

  • Correct
    • Combining all the javascript in one file
    • Having the javascript in the footer
    • Minimized the number of javascript files
  • Incorrect
    • Native file type should be .js
    • If you don’t add actual php code in the php file, what’s the point because:
      • you loose any manipulation by plugins/hooks
      • javascript should be in a javascript file
      • you can not exclude any of it on any page
      • you can not check dependencies

Move all the javascript to a .js file and then enqueue it with

wp_enqueue_script( $handle, $src = false, $deps = array(), 
    $ver = false, $in_footer = false );

So you can use @Furqan is method:

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script',
        get_template_directory_uri() . '/js/custom_script.js',
        array('jquery'),
        '1.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
  • $handle should be a unique name (so don’t use custom-script).
  • $src the path to the file (http:// uri not file path)
  • $deps an array of dependencies. He added jquery for you (handle names)
  • $ver is the version number
  • $in_footer should be true for all non-execute-as-quick-as-possible scripts

Leave a Comment