jQuery is a fast, small, and feature-rich JavaScript library. It makes it easier to manipulate HTML documents, handle events, create animations, and develop interactive user interfaces. By default, WordPress includes jQuery, but it may not always be the latest version. In this article, we’ll show you how to load jQuery from a Content Delivery Network (CDN) in WordPress.
Why Load jQuery from a CDN?
There are several reasons why you may want to load jQuery from a CDN instead of using the version that comes with WordPress.
- Improved Performance: A CDN distributes content to multiple servers worldwide. When a user visits your website, they will be served the content from the nearest server, reducing the latency and improving the loading time.
- Better Caching: Loading jQuery from a CDN allows the browser to cache the file, reducing the amount of data that needs to be downloaded every time the user visits your website.
- Reliability: By relying on a large and well-established CDN, you can be confident that the jQuery library will be available and accessible to your users at all times.
How to Load jQuery from a CDN in WordPress
To load jQuery from a CDN in WordPress, you need to modify your theme or create a plugin. Here’s what you need to do:
Add the following code to your theme’s functions.php file or in a plugin file:
function crunchify_load_jquery_from_google_cdn() { if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://code.jquery.com/jquery-3.6.3.min.js', false, '3.6.0'); wp_enqueue_script('jquery'); } } add_action('wp_enqueue_scripts', 'crunchify_load_jquery_from_google_cdn');
This code deregisters the default jQuery script
that is included with WordPress and replaces it with the version from the jQuery CDN.
Verify that jQuery is being loaded from the CDN by checking the source code of your website. In your browser, right-click on the page and select “View Page Source”. Then search for “jquery” to see if the URL in the script tag matches the CDN URL.
Note: It’s important to make sure that the CDN is reliable and that the version of jQuery you’re using is compatible with your WordPress theme and plugins. If you encounter any issues, you may need to switch back to the default version of jQuery included with WordPress.
Using a Different CDN – Google CDN
You can also use a different CDN, such as Google
, to load jQuery in WordPress. Here’s the code to use the Google CDN:
function crunchify_load_jquery_from_google_cdn() { if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js', false, '3.6.0'); wp_enqueue_script('jquery'); } } add_action('wp_enqueue_scripts', 'crunchify_load_jquery_from_google_cdn');
Let me know if you have any question or issue loading jQuery on your site.
The post How to Load jQuery from a CDN in WordPress? appeared first on Crunchify.
0 Commentaires