google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Hướng dẫn cách chuyên nghiệp để nạp JavaScript trong Wordpress WordPress - một nền tảng mã nguồn mở PHP cực kì mạnh mẽ dùng để phát triển blog cá nhân; WordPress có thể được xem là hệ thống blog được sử dụng nhiều nhất hiên nay, và tôi cũng vừa mới khai trương một trang blog cá nhân trên hệ thống này.

Tại thời điểm bài viết này, tổ chức sáng lập WordPress vừa phát hành phiên bản 3 - một bản nâng cấp cực kì đáng giá. Và nếu bạn là một nhà phát triển blog cá nhân dựa trên nền tảng này, hẳn bạn cũng biết các nhược điểm của WordPress, một trong số chúng là cách tổ chức dữ liệu, mã nguồn dường như đều thay đổi mỗi lần WordPress được nâng cấp.

Chỉ tính riêng vấn đề nạp thư viện JavaScript trong hệ thống WordPress, mỗi phiên bản đều có cách quản lí riêng. Vậy dưới góc độ của một nhà phát triển web, chúng ta nên dùng giải pháp nào để việc quản lí trở nên hiệu quả hơn? Hãy vào trang chi tiết để xem hướng dẫn nạp JavaScript trong Wordpress với cách chuyên nghiệp nhất.


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

If you're involved in WordPress development, a challenge that you're going to face sooner or later is how to include JavaScript files efficiently.

In this tutorial, I'm going to show you the best way to do that.

Let's say you have a plugin that adds a custom shortcode. The shortcode needs some JavaScript code which requires jQuery.

If you're just starting out with WordPress development, you might be tempted to write something like this:

How a WordPress Youngling does it

add_action('wp_head', 'add_my_script');
 
function add_my_script() { ?>
<script type="text/javascript" src="/javascript/article/How_to_load_JavaScript_like_a_WordPress_Master.php/<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/jquery.js"></script>

<script type="text/javascript" src="/javascript/article/How_to_load_JavaScript_like_a_WordPress_Master.php/<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/my-script.js"></script>
<?php }

Let's see what's wrong with that approach:

Firstly, since WordPress 2.6, the user can move the wp-content directory wherever he wants. What does that mean? That's right: instant plugin breakage.

Secondly, if the user installs another plugin that also uses jQuery, the page will end up with jQuery being loaded twice.

Fortunately, WordPress lends us a hand with these two problems:

How a young Padawan does it

add_action('template_redirect', 'add_my_script');

 
function add_my_script() {
	wp_enqueue_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);

}

The above script ultimately does what the first one does, except:

  • it gets the correct path for the file
  • it checks if jQuery has already been included or not
  • the script tag is written in the footer, so the page loads faster

That's an obvious improvement. But what if the shortcode appears on a single page?

You're needlessly including a file 99% of the time, causing slower page loads.

Notice that in the last two examples, we've been using the template_redirect action.

The trouble with wp_enqueue_script() is that you have to call it before wp_head() fires. So, before the page is rendered, you have to decide if you should add your script or not. Not an easy call to make, is it?

Well, there's a secret method that will let you enqueue scripts after the entire page has been displayed.

The Jedi Knight way

add_action('wp_footer', 'print_my_script');
 
function print_my_script() {

	global $add_my_script, $wp_scripts;
 
	if ( ! $add_my_script )

		return;
 
	wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);

 
	$wp_scripts->do_items('my-script');
}

In this case, the script will be enqueued only if the $add_my_script global was set at some point during the rendering of the page.

The key here is that you're calling $wp_scripts directly, instead of relying on WordPress to do it for you.

It will still check if jQuery was already enqueued or not.

You can set the $add_my_script flag from any function or method, including from a shortcode handler:

add_shortcode('myshortcode', 'my_shortcode_handler');

 
function my_shortcode_handler($atts) {
	global $add_my_script;
 

	$add_my_script = true;
 
	// actual shortcode handling here
}

So, the script will be added if [myshortcode ...] was found in any of the posts on the current page.

Nothing more to do here, except wrap it up in a nice class:

The Jedi Master way

class My_Shortcode {
	static $add_script;
 
	function init() {

		add_shortcode('myshortcode', array(__CLASS__, 'handle_shortcode'));
		add_action('wp_footer', array(__CLASS__, 'add_script'));

	}
 
	function handle_shortcode($atts) {
		self::$add_script = true;

 
		// actual shortcode handling here
	}
 
	function add_script() {

		global $wp_scripts;
 
		if ( ! self::$add_script )

			return;
 
		wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);

 
		$wp_scripts->do_items('my-script');
	}
}
 
My_Shortcode::init();

I hope this tutorial has helped you on your way to mastering WordPress script loading.

Further reading:

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web