Hiểu đúng về wp_enqueue_script vs wp_register_script trong wordpress

Nội dung

wp_register_script() dùng để đăng ký một thư viện script.

wp_enqueue_script() dùng để đăng ký và sử dụng một thư viện script.

Bạn có thể không cần sử dụng hàm wp_register_script() mà trực tiếp gọi hàm wp_enqueue_script()

Vậy wp_register_script() có vai trò gì?

Hãy xem ví dụ sau đây:

				
					function my_enqueue_scripts()
{
wp_register_script( 'first', get_template_directory_uri() . 'js/first.js' );

wp_enqueue_script( 'second', get_template_directory_uri() . 'js/second.js', array( 'first' ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
				
			

first.js sẽ chỉ được “load” (trước second.js) khi second.js được “load”.

Xem tiếp 1 ví dụ dưới đây:

				
					add_action("wp_enqueue_scripts", "myscripts");
function myscripts() { 
    wp_register_script('myfirstscript', 
                        get_template_directory_uri() .'/myscript.js',   //
                        array ('jquery', 'jquery-ui'),                  //depends on these, however, they are registered by core already, so no need to enqueue them.
                        false, false);
    wp_enqueue_script('myfirstscript');
      
}
				
			

myfirstscript phụ thuộc vào các thư viện jquery, jquery-ui nhưng không cần phải load chúng vì chúng đã được đăng ký trong hệ thống wordpress.

Cùng chủ đề
Mỗi website một câu chuyện
Góc chia sẻ

Lập trình website