Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Så här ersätter du standard WordPress jQuery-skript med Google Library

Vill du ersätta WordPress standard jQuery-skript med jQuery från Google Hosted Libraries?

WordPress innehåller jQuery som standard med core-programvaran. Om du byter ut den mot den senaste jQuery-versionen från Googles bibliotek kan du dock förbättra prestandan.

I den här artikeln visar vi hur du enkelt kan ersätta WordPress standard jQuery-skript med Google-bibliotek för att förbättra prestanda och hastighet.

Replacing the WordPress jQuery with Google library

Varför & när du bör ersätta standard WordPress jQuery

jQuery är ett populärt JavaScript-bibliotek som används av utvecklare för att skapa beautiful webbapplikationer. Det används ganska ofta i WordPress för att add to funktioner som gillar sliders, popups och mycket mer.

WordPress innehåller ett jQuery-bibliotek som ingår i WordPress core. Många av de högst upp WordPress tillägg och mest populära WordPress teman förlitar sig på detta bibliotek för viktiga funktioner och funktioner.

JQuery and other third-party scripts packaged in WordPress

Att hämta jQuery på en server på ett delat webbhotell kan dock vara resurskrävande och göra din site långsammare, särskilt om du använder dåligt kodade WordPress teman eller tillägg som inte följer WordPress bästa praxis.

En annan issue med att använda den jQuery-version som ingår i WordPress är att den inte kommer att updates om inte WordPress uppdaterar den. Det kan finnas nyare versioner av jQuery med prestanda eller säkerhets fixar, men du kommer inte att få tillgång till dem förrän de ingår i en WordPress update.

Det finns några lösningar för att fixa detta. You kan till exempel hämta jQuery via Googles servrar eller jQuerys officiella CDN.

Google Hosted Libraries är ett bra val eftersom deras servrar är stabila, uppdaterade och mycket optimerade för hastighet vilket allow jQuery att hämta mycket snabbare på din WordPress site.

Med detta sagt, låt oss ta en titt på hur du enkelt kan ersätta standard WordPress jQuery med Google-biblioteket.

Ersätt standard WordPress jQuery med Google Library

WordPress har en built-in metod för att enkelt add to skript och stylesheets. This also allows you to safely remove any scripts or stylesheets that are loaded using the built-in method.

Vi kommer att använda den här metoden för att först inaktivera WordPress standard jQuery. Därefter säger vi till WordPress att hämta jQuery via Googles bibliotek.

Du måste lägga till följande kod i ditt temas functions.php-fil, ett site-specifikt plugin eller ett code snippets plugin.

function wpb_modify_jquery() {
    //check if front-end is being viewed
    if (!is_admin()) {
        // Remove default WordPress jQuery
        wp_deregister_script('jquery');
        // Register new jQuery script via Google Library    
        wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js', false, '3.6.0');
        // Enqueue the script   
        wp_enqueue_script('jquery');
    }
}
// Execute the action when WordPress is initialized
add_action('init', 'wpb_modify_jquery');

Vi rekommenderar att du använder WPCode code snippets plugin för att add to denna kod i WordPress. Det är gratis, användarvänligt och kommer inte att förstöra din website om något går fel.

Obs: Det finns också en premiumversion av WPCode som erbjuder avancerade funktioner som kodrevisioner, automatiska konvertering Pixels, tidsinställda snippor, ett privat molnbibliotek och mer.

För att komma igång måste du installera och aktivera WPCode. Om du behöver hjälp kan du läsa vår guide om hur du installerar ett plugin för WordPress.

När pluginet är aktiverat navigerar du till Code Sn ippets Add Snippet från din WordPress dashboard. Därifrån hittar du alternativet ”Add Your Custom Code (New Snippet)” och klickar på knappen ”Use snippet” under det.

Add a new custom code snippet in WPCode

Därefter kan du add to en rubrik för ditt code snippet. Det kan vara vad som helst som hjälper dig att komma ihåg vad koden är till för.

Efter det klistrar du bara in koden ovan i boxen ”Code Preview” och väljer ”PHP Snippet” som code type från dropdown-menyn.

Paste code snippet into WPCode

Till sist togglar du omkopplaren från ”Activate” till ”Inaktiverad” och klickar på knappen ”Save Snippet”.

Activate and save your custom code snippet

Nu är det all! WordPress kommer nu att ersätta standard jQuery och hämtar den via Googles bibliotek istället.

Note: Den här metoden fortsätter att hämta den jQuery-version som nämns i URL:en. I framtiden kan du behöva ändra URL:en till Googles bibliotek för att använda en nyare jQuery-version.

Google uppdaterar inte versionsnumret automatiskt åt you eftersom det kan orsaka kompatibilitetsproblem om ditt theme eller dina tillägg förlitar sig på en annan version.

Du kan hitta den senaste URL:en genom att besöka Googles website för hosted libraries.

Google hosted libraries - jQuery

Därifrån kan du också hitta URL: erna för äldre versioner av jQuery som du kan använda för felsökning om det behövs.

Byta ut andra standard jQuery-bibliotek

Förutom core jQuery-biblioteket innehåller WordPress också en massa andra jQuery-skript. Några av dessa skript, gillar jQuery Mobile och jQuery UI, är hosted på Google-biblioteket.

För andra bibliotek kan du använda jQuerys egna CDN-servrar för att hämta dem mycket snabbare. I Följer exempel har vi ersatt WordPress jquery-ui-core-skriptet med den officiella jquery-ui-versionen.

function wpb_modify_jquery_ui() {
if (!is_admin()) {
wp_deregister_script('jquery-ui-core');
wp_register_script('jquery-ui-core', 'https://code.jquery.com/ui/1.12.1/jquery-ui.min.js', false, '1.12.1');
wp_enqueue_script('jquery-ui-core');
    }
}
add_action('init', 'wpb_modify_jquery_ui');

Precis som med Googles bibliotek måste du byta ut URL:en efter ett tag för att använda den senaste versionen av skriptet.

Inaktivera jQuery helt och hållet i WordPress

På grund av den omfattande användningen rekommenderar vi inte att du inaktiverar jQuery helt på din WordPress website. Även om din WordPress Theme inte använder jQuery, behöver många populära WordPress Plugins det fortfarande.

Men om du är säker på att din website inte behöver jQuery kan du inaktivera det på ett säkert sätt.

Lägg bara till följande kod i ditt temas functions-fil, ett site-specifikt plugin eller ett code snippets plugin som WPCode.

if ( !is_admin() ) wp_deregister_script('jquery');

Det är all. Den här koden inaktiverar helt enkelt jQuery-skriptet från att hämta på the front end av din WordPress website.

Felsökning av jQuery-relaterade issues i WordPress

Nya versioner av jQuery kan ibland deprecated, eller remove, gamla metoder och funktioner. Om ett WordPress tillägg på din website använder en äldre metod, kan detta potentiellt förstöra saker.

You may notice warnings in the Console area of the Inspect tool, or you may notice some features have just stopped working.

WordPress brukade använda ett skript som heter jQuery-migrate för att ge backup-kompatibilitet med äldre versioner av jQuery. Men sedan WordPress 5.5 har detta skript dragits tillbaka från WordPress.

Om du vill add to jQuery-migrate-skriptet igen eller troubleshoota mellan olika jQuery-versioner kan du prova följande metod.

Installera och aktivera bara plugin-programmet Version Control for jQuery. För mer detaljer, se vår steg-för-steg guide om hur du installerar ett WordPress plugin.

Efter aktivering måste du besöka Settings ” jQuery Version Control page. Härifrån kan du välja den jQuery-version du vill använda.

Tillägget kommer automatiskt att hämta den versionen från det officiella jQuery CDN.

jQuery version control

Pluginet kommer också att hämta jQuery migrate-skriptet. Om du vill kan du inaktivera det under felsökningen.

Glöm inte att clicka på knappen ”Save Changes” för att spara dina ändringar.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du ersätter standard WordPress jQuery med Google-biblioteket. Du kanske också vill se dessa användbara jQuery tutorials för WordPress-användare eller se vår kompletta WordPress guide för prestandaoptimering.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

28 kommentarerLämna ett svar

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. ALEX says

    Hello,

    We have a server in China, and all of resource from Google are blocked by Chinese government firewall.

    But, the Jquery and Fonts resources are loaded from Google on WordPress by default now, and the site is caused seriously delay.

    So, is there anyway to force Js or CSS resources to be loaded from local server please?

    Thanks

    • WPBeginner Support says

      If you have a web address for the jquery files on a local server then you would change the url in the snippet to point toward where the jquery is located.

      Administratör

  3. Wilbur says

    Hey, sorry for haling this post out of the grave… :) How relevant is this still? In Terms of the latest P Core versions?

    Thanks

  4. Jorge says

    Hi,

    Here is a more advanced implementation:

    add_action( ’wp_enqueue_scripts’, ’register_jquery’ );
    function register_jquery() {
    if (!is_admin()) {
    wp_deregister_script(’jquery-core’);
    wp_register_script(’jquery-core’, ’http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js’, true, ’1.11.3’);
    wp_enqueue_script(’jquery-core’);
    wp_deregister_script(’jquery-migrate’);
    wp_register_script(’jquery-migrate’, ’http://cdn.yourdomain.com/wp-includes/js/jquery/jquery-migrate.min.js’, true, ’1.2.1’);
    wp_enqueue_script(’jquery-migrate’);
    }
    }

    Where ”cdn.yourdomain.com” it should be replaced by the file path, using a CDN for a better result.

    Best Regards,

    Jorge Ortiz

      • Plato39 says

        Jorge’s code worked for me – but the quotation marks must be replaced. Try this:

        add_action( ’wp_enqueue_scripts’, ’register_jquery’ );
        function register_jquery() {
        if (!is_admin()) {
        wp_deregister_script(’jquery-core’);
        wp_register_script(’jquery-core’, ’https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js’, true, ’1.11.3’);
        wp_enqueue_script(’jquery-core’);
        wp_deregister_script(’jquery-migrate’);
        wp_register_script(’jquery-migrate’, ’http://cdn.yourdomain.com/wp-includes/js/jquery/jquery-migrate.min.js’, true, ’1.2.1’);
        wp_enqueue_script(’jquery-migrate’);
        }
        }

        • Plato39 says

          OK – it’s this webpage that is adding the fancy quotes. Just do a ’find and replace’ in your text editor (or manually replace the quotes with plain ones) and the code will work in your theme’s functions.php file.

  5. will says

    hi
    thank you very much for your post, I tried to change it and do not know if I did well because my web now is 2 seconds slower
    How do I check if I did well and I’m using the google libraries?

  6. Ihsan says

    I tested code above and i replace the last line with this to make it work and better

    add_action( ’wp_print_scripts’, ’modify_jquery’, 100 );

  7. Alejandro says

    Hi, Thank you for your tips. I do not know Why when using this function, the jquery from Google is loading twice, I mean, I have two HTTP request instead of one, Here is the test: http://tools.pingdom.com/fpt/#!/dROQaF/http://elbauldelprogramador.com.

    With jquery.easing the same happends, but this time with 3 HTTP request for the same file.

    Any ideas? I’ve been looking into the code but didn’t find duplication of wp_enqueue_script(”);

    Thank you in advance

  8. Joseph Chambers says

    What if I want to load either HTTP or HTTPS based on whatever the visitor is visiting our page on.

    for most things we can change: http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js -> //ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js and it works. However; something in the wp_register_script() is throwing a error ( White page with the word: Error ) when I change that. thoughts, solutions?

  9. Riversatile says

    Hi,

    Here is the latest version of the googleapi jquery file.

    When you copy/paste the code above, don’t forget to replace the jquery URl by this one :

    http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

    Then replace ”1.4.4” by ”1.6.2”

    Like that :

    //Making jQuery Google APIfunction modify_jquery() { if (!is_admin()) { // comment out the next two lines to load the local copy of jQuery wp_deregister_script(’jquery’); wp_register_script(’jquery’, ’http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js’, false, ’1.6.2’); wp_enqueue_script(’jquery’); }}add_action(’init’, ’modify_jquery’);

    • vnu says

      Could anyone tell me if I need to modify (!is_admin) to ”minimum” capability if I use a plugin plugin like thethefly ’s tabs and accordions . So the tabs created on pages are view-able by everyone?

      Thanks !

  10. Melissa Cleaver says

    Thanks so much for the code, but when I tried to use it in my functions.php file, I got a fatal error, no matter where in the code I put it. Am I doing something wrong here?

  11. swanie says

    Question: does Google Library do a good job at pulling in the alt tag info from the media library? … I have several professional themes that use a main page jQuery slider, but they don’t pull in the alt tag … thus, the source code look like: alt=”” … which of course, is an seo no-no. I’ve never used the Google Library script … I’d be curious how that works. What’s your experience?

      • swanie says

        OK … I guess I’m specifically talking about jQuery sliders … I have purchased several professional themes with a main page jQuery slider … here’s one of them: http://coloradospringsautomechanics.com … if you view source, it pulls in the images, but not the alt tags … the alt tag is empty.

        I guess by reading this post, this Google Library approach could possibly resolve that.

        Another solution could be to break open the plugin files and add to the alt tag so I should have:

        img src=”file.jpg” alt=”” title=””

        Just wondering why these jQuery sliders don’t pull in the alt tags. That make sense? Am I off-subject?

        You guys rock, by the way.

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.