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

Come sostituire lo script jQuery predefinito di WordPress con la libreria di Google

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Volete sostituire lo script jQuery predefinito di WordPress con jQuery delle Librerie ospitate da Google?

WordPress include jQuery nel software di base in modo predefinito. Tuttavia, la sostituzione con l’ultima versione di jQuery della libreria di Google può migliorare le prestazioni.

In questo articolo vi mostreremo come sostituire facilmente lo script jQuery predefinito di WordPress con la libreria di Google per migliorare le prestazioni e la velocità.

Replacing the WordPress jQuery with Google library

Perché e quando si dovrebbe sostituire il jQuery predefinito di WordPress

jQuery è una popolare libreria JavaScript utilizzata dagli sviluppatori per creare splendide applicazioni web. Viene utilizzata spesso in WordPress per aggiungere caratteristiche come cursori, popup e molto altro.

WordPress include una libreria jQuery nel pacchetto del software principale di WordPress. Molti dei plugin WordPress in alto e dei temi WordPress più popolari si affidano a questa libreria per funzionalità e caratteristiche essenziali.

JQuery and other third-party scripts packaged in WordPress

Tuttavia, il caricamento di jQuery su un server di hosting condiviso può richiedere un notevole dispendio di risorse e rallentare il sito, soprattutto se si utilizzano temi o plugin per WordPress mal codificati che non seguono le best practice di WordPress.

Un altro problema dell’utilizzo della versione di jQuery inclusa in WordPress è che non viene aggiornata a meno che WordPress non la aggiorni. Potrebbero esserci nuove versioni di jQuery con correttivi alle prestazioni o alla sicurezza, ma non sarà possibile accedervi finché non saranno incluse in un aggiornamento di WordPress.

Esistono alcuni rimedi per correggere questo problema. Ad esempio, è possibile caricare jQuery tramite i server di Google o il CDN ufficiale di jQuery.

Le librerie ospitate da Google sono una buona scelta perché i loro server sono stabili, aggiornati e altamente ottimizzati per la velocità, il che permette a jQuery di caricarsi molto più velocemente sul vostro sito WordPress.

Detto questo, vediamo come sostituire facilmente il jQuery predefinito di WordPress con la libreria di Google.

Sostituire jQuery predefinito di WordPress con la libreria di Google

WordPress dispone di un metodo integrato per aggiungere facilmente script e fogli di stile. Ciò consente anche di rimuovere in modo sicuro gli script o i fogli di stile caricati con il metodo incorporato.

Utilizzeremo questo metodo per disabilitare innanzitutto il jQuery predefinito di WordPress. Dopodiché, diremo a WordPress di caricare jQuery tramite la libreria di Google.

È necessario aggiungere il seguente codice al file functions.php del tema, a un plugin specifico per il sito o a un plugin di snippets di codice.

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');

Si consiglia di utilizzare il plugin WPCode code snippets per aggiungere questo codice in WordPress. È gratuito, facile da usare e non romperà il vostro sito web se qualcosa va storto.

Nota: esiste anche una versione premium di WPCode che offre caratteristiche avanzate come le revisioni del codice, gli sgranati automatici di conversione, gli snippet programmati, una libreria cloud privata e altro ancora.

Per iniziare, è necessario installare e attivare WPCode. Se avete bisogno di aiuto, consultate la nostra guida su come installare un plugin di WordPress.

Una volta attivato il plugin, navigare su Code Snippets Aggiungi snippet dalla dashboard di WordPress. Da qui, trovare l’opzione “Aggiungi il tuo codice personalizzato (nuovo snippet)” e fare clic sul pulsante “Usa snippet” sotto di essa.

Add a new custom code snippet in WPCode

Successivamente, si può aggiungere un titolo per lo snippet di codice. Può essere qualsiasi cosa che aiuti a ricordare a cosa serve il codice.

A questo punto, è sufficiente incollare il codice di cui sopra nella casella “Anteprima codice” e selezionare “PHP Snippet” come tipo di codice dal menu a discesa.

Paste code snippet into WPCode

Infine, spostare l’interruttore da ‘Inattivo’ ad ‘Attivo’ e fare clic sul pulsante ‘Salva snippet’.

Activate and save your custom code snippet

Tutto-in-uno! WordPress ora sostituirà il jQuery predefinito e lo caricherà invece tramite la libreria di Google.

Nota: questo metodo continuerà a caricare la versione di jQuery indicata nell’URL. In futuro, potrebbe essere necessario modificare l’URL della libreria di Google per utilizzare una versione di jQuery più recente.

Google non aggiornerà automaticamente il numero di versione perché potrebbe causare problemi di compatibilità se il tema o i plugin si basano su una versione diversa.

È possibile trovare l’ultimo URL visitando il sito web delle biblioteche ospitate da Google.

Google hosted libraries - jQuery

Da qui è possibile trovare anche gli URL delle versioni precedenti di jQuery, che possono essere utilizzati per la risoluzione dei problemi, se necessario.

Sostituzione di altre librerie jQuery predefinite

Oltre alla libreria jQuery di base, WordPress include anche una serie di altri script jQuery. Alcuni di questi script, come jQuery Mobile e jQuery UI, sono ospitati sulla libreria di Google.

Per le altre librerie, è possibile utilizzare i server CDN di jQuery per caricarle molto più velocemente. Nell’esempio seguente, abbiamo sostituito lo script WordPress jquery-ui-core con la versione ufficiale di jquery-ui.

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');

Come per le librerie di Google, è necessario sostituire l’URL dopo un po’ di tempo per utilizzare l’ultima versione dello script.

Disabilitare completamente jQuery in WordPress

A causa del suo ampio utilizzo, non consigliamo di disabilitare completamente jQuery sul vostro sito web WordPress. Anche se il vostro tema WordPress non utilizza jQuery, molti plugin WordPress popolari ne hanno ancora bisogno.

Tuttavia, se siete certi che il vostro sito web non ha bisogno di jQuery, potete tranquillamente disabilitarlo.

È sufficiente aggiungere il seguente codice al file functions del tema, a un plugin specifico per il sito o a un plugin di snippets di codice come WPCode.

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

Tutto-in-uno. Questo codice disabilita semplicemente il caricamento dello script jQuery sul frontend del vostro sito web WordPress.

Risoluzione dei problemi relativi a jQuery in WordPress

Le nuove versioni di jQuery possono talvolta deprecare o rimuovere vecchi metodi e funzioni. Se un plugin di WordPress sul vostro sito web utilizza un vecchio metodo, questo potrebbe potenzialmente rompere le cose.

Potreste notare delle attenzioni nell’area Console dello strumento Inspect, oppure potreste notare che alcune caratteristiche hanno smesso di funzionare.

WordPress utilizzava uno script chiamato jQuery-migrate per fornire la compatibilità di backup con le versioni precedenti di jQuery. Tuttavia, a partire da WordPress 5.5 questo script è stato ritirato da WordPress.

Se si desidera aggiungere nuovamente lo script jQuery-migrate o risolvere i problemi tra diverse versioni di jQuery, si può provare il metodo seguente.

È sufficiente installare e attivare il plugin Version Control for jQuery. Per maggiori dettagli, consultate la nostra guida passo passo su come installare un plugin di WordPress.

Dopo l’attivazione, è necessario visitare la pagina Impostazioni ” Controllo della versione di jQuery. Da qui è possibile scegliere la versione di jQuery che si desidera utilizzare.

Il plugin caricherà automaticamente quella versione dal CDN ufficiale di jQuery.

jQuery version control

Il plugin carica anche lo script jQuery migrate. Se si desidera, è possibile disabilitarlo durante la risoluzione dei problemi.

Non dimenticate di fare clic sul pulsante “Salva le modifiche” per salvare le modifiche.

Speriamo che questo articolo vi abbia aiutato a capire come sostituire il jQuery predefinito di WordPress con la libreria di Google. Potreste anche voler consultare questi utili tutorial su jQuery per utenti di WordPress o la nostra guida completa all’ottimizzazione delle prestazioni di WordPress.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

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.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

28 commentiLascia una risposta

  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.

      Admin

  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.

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.