Use ‘$’ instead of ‘jQuery’ in WordPress

jqueryLike any good WordPress developer knows, the correct way to load jQuery in WordPress is not calling the Google Hosted Libraries. And no, it’s not downloading jQuery and declaring <head> script </ head>. No, the correct form is calling with wp_enqueue_script .

 

wp_enqueue_script("jquery");

With this in a function associated with the action add_action ” wp_enqueue_script “jQuery is already loaded in the system.

However, it is loaded in ” safe “. What does it mean this? If you have programmed before jQuery, sure you’ve used a lot a dollar sign ($). This symbol replaces the word “jQuery”, making the scripts are shorter and lighter in weight. While in safe mode, WordPress does not recognize the $ symbol as something about jQuery, so that does not conflict with other libraries also use the dollar.

So we can not use the dollar? Yes and no . Always under your own risk and we can re-activate the dollar as a substitute for the word jQuery . This is achieved by encapsulating our javascript code inside a function, which will vary depending on how your code is loaded into the header or footer.

If your code is loaded in the footer , we can do this:

(function($) {

	// Ahora puedes usar $. Puedes comprobarlo usando la siguiente línea:
	// console.log($);
        // Recuerda que solo puedes usar $ DENTRO de esta función.

})( jQuery );

If it is absolutely necessary that your code is in the header , then you should use this other encapsulation:

jQuery(document).ready(function( $ ) {

	// Ahora puedes usar $. Puedes comprobarlo usando la siguiente línea:
	// console.log($);
        // Recuerda que solo puedes usar $ DENTRO de esta función.

});

And that’s it. Simple as that. First wp_enqueue_script loads jQuery, and then encapsulate your code as one of these two functions. You can go back to using the dollar to make lighter and easier to write your code.

“Good programmers use their brains, but some
good guidelines save us having to do it in each case . ” 

– Francis Glassborow

¿Te ha gustado el artículo?
Sé el primero en calificar esta publicación.
1 Star2 Stars3 Stars4 Stars5 Stars
Loading...
Artículo escrito por

¡Exprésate! Dejanos tu comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *



Aún no hay comentarios en esta entrada. ¿Te animas?