Move Javascript from head to footter in wordpress

0

I want to put all the Javascript that appear in the header of wordpress add them in the footter to make the web faster, how should I do it?

    
asked by AitorUdabe 16.09.2016 в 09:49
source

1 answer

1

With the wp_enqueue_scripts function.

For example, to pass jQuery to footer , something like this would be done:

wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' );

$handle = 'jquery'
$src = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' 
$deps = array('jquery')
$version = '2.1.1'
$in_footer = false
wp_enqueue_script($handle, $src, $deps, $version, $in_footer);

On the first line, you remove the jQuery of WordPress from the script queue, because it puts it in the header .

In the second line you register a script to go to the queue, the parameters of this function are the same as those of the following:

The function you need is wp_enqueue_script that takes five parameters:

  • $handle - It is the identifier of the script, it must be unique and it is mandatory.
  • $src - It is the path to the script, it is mandatory
  • $deps - It indicates the dependencies that the script needs to be able to be glued, it is an array, but it is optional.
  • $version - Used to add a version tag, it's optional.
  • $in_footer - This is an optional Boolean . If true they are placed before </head> , if they are false they go before </fotee33r> .

In real life, the use of these functions looks like this:

/* *** jQuery 2.1.1 *** */
add_action( 'wp_enqueue_scripts', 'jQuery211', 99);
function jQuery211() {
  wp_deregister_script( 'jquery' );
  wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' );
  wp_enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', array( 'jquery' ), '2.1.1', false );
}

The function has some notes that you should know: link

    
answered by 16.09.2016 / 15:46
source