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 lägger du till JavaScript och Styling i WordPress på rätt sätt

Vill du lära dig hur du lägger till JavaScript och CSS stylesheets på rätt sätt i WordPress?

Många DIY-användare gör ofta misstaget att direkt anropa sina skript och stylesheets i tillägg och teman.

I den här artikeln visar vi dig hur du lägger till JavaScript och stylesheets i WordPress på rätt sätt. Detta är till viss nytta för dig som precis har börjat lära dig att utveckla teman och plugins för WordPress.

Properly adding JavaScripts and styles in WordPress

Vanliga misstag när du lägger till skript och stylesheets i WordPress

Många new WordPress-plugins och temautvecklare gör misstaget att direkt lägga till sina skript eller inline CSS i sina tillägg och themes.

Vissa använder felaktigt funktionen wp_head för att hämta sina skript och stylesheets.

<?php
add_action('wp_head', 'wpb_bad_script');
function wpb_bad_script() {
echo 'jQuery goes here';
}
?>

Även om koden ovan kan verka enklare är det fel sätt att lägga till skript i WordPress, och det leder till fler konflikter i framtiden.

Om du till exempel laddar jQuery manuellt och ett annat plugin laddar jQuery genom rätt metod, då hämtar du jQuery två gånger. Om det hämtas på varje page kommer det att påverka WordPress hastighet och prestanda negativt.

Det är också möjligt att de två är olika versioner, vilket också kan orsaka konflikter.

Med detta sagt, låt oss ta en titt på det rätta sättet att lägga till skript och stylesheets.

Varför Enqueue-skript och Styles i WordPress?

WordPress har en stark gemenskap av utvecklare. Tusentals människor från hela världen utvecklar themes och tillägg för WordPress.

För att se till att allt fungerar som det ska och att ingen trampar någon på tårna har WordPress ett kösystem. Detta system tillhandahåller ett programmerbart sätt att hämta JavaScripts och CSS stylesheets.

Med hjälp av funktionerna wp_enqueue_script och wp_enqueue_style talar du om för WordPress när en fil ska hämtas, var den ska hämtas och vilka beroenden den har.

Detta system allow också utvecklare att använda de built-in JavaScript-bibliotek som levereras med WordPress i stället för att hämta samma tredjepartsskript flera gånger. Detta minskar tiden för att hämta sidor och hjälper till att undvika konflikter med andra themes och tillägg.

Hur gör jag för att köa skript på rätt sätt i WordPress?

Att hämta skript på rätt sätt i WordPress är mycket enkelt. Under är ett exempel på kod som du skulle klistra in i din plugins-fil, i ditt temas functions.php-fil, eller i ett code snippets plugin för att korrekt ladda skript i WordPress.

?php
function wpb_adding_scripts() {
 
wp_register_script('my_amazing_script', plugins_url('amazing_script.js', __FILE__), array('jquery'),'1.1', true);
 
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

Förklaring:

Vi började med att registrera vårt skript med hjälp av funktionen wp_register_script(). Denna funktion godkänner 5 parametrar:

  • $handle – Handle är det unika namnet på your script. Vårt anropas ”my_amazing_script”
  • $src – src är location för your script. Vi använder funktionen plugins_url för att få rätt URL till vår folder med tillägg. När WordPress hittar den kommer den att leta efter vårt filnamn amazing_script.js i den foldern.
  • $deps – deps står för dependency (beroende). Eftersom vårt skript använder jQuery har vi lagt till jQuery i dependency area. WordPress kommer automatiskt att hämta jQuery om det inte redan hämtar det på webbplatsen.
  • $ver – Detta är versionsnumret för vårt skript. Denna parameter är ej obligatorisk.
  • $in_footer – Vi vill ladda vårt skript i footern, så vi har satt värdet till true. Om du vill hämta skriptet i Headern, då gör du det till false.

När vi har angett alla parametrar i wp_register_script kan vi bara anropa skriptet i wp_enqueue_script() som får allt att hända.

Det sista steget är att använda åtgärds-hooken wp_enqueue_scripts för att faktiskt hämta skriptet. Eftersom detta är en exempelkod har vi add to den precis under allt annat.

Om du lägger till detta i ditt tema eller plugin, kan du placera denna åtgärds-hook där skriptet faktiskt är obligatoriskt. This allows you to reduce the memory footprint of your plugin.

Nu kanske vissa undrar varför vi går det extra steget att registrera skriptet först och sedan sätta det i kö? Tja, detta tillåter andra webbplatsägare att avregistrera ditt skript utan att ändra kärnkoden för ditt plugin.

Korrekt Enqueue av Styles i WordPress

Precis som skript kan du också enqueuea dina stylesheets. Titta på exemplet under:

<?php
function wpb_adding_styles() {
wp_register_style('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );  
?>

I stället för att använda wp_enqueue_script använder vi nu wp_enqueue_style för att add to vår stylesheet.

Notice that we have used wp_enqueue_scripts action hook for both styles and scripts. Trots namnet fungerar den här funktionen för båda.

I exemplen ovan har vi använt funktionen plugins_url för att peka på location för det skript eller den style som vi vill enqueuea.

Men om du använder funktionen enqueue scripts i ditt theme, använd då helt enkelt get_template_directory_uri() istället. Om du arbetar med ett barntema, använd då get_stylesheet_directory_uri().

Under följer ett exempel på kod:

<?php
  
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', get_template_directory_uri() . '/js/amazing_script.js', array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du lägger till JavaScript och stilar på rätt sätt i WordPress. Du kanske också vill studera källkoden för de bästa WordPress-tilläggen för några verkliga kodexempel eller kontrollera vår guide om hur du enkelt lägger till JavaScript i WordPress-poster eller pages.

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

36 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. Jean-Michel says

    Hi there,
    I followed what is said here but now I get an empty white page on my web site. Could someone give me a hint ?
    Thanks

  3. Zaved Hossain says

    This is nice, though my usual practice is to add wp_enqueue_script/style in a single line without registering. Coders need to be careful about the parameters, perhaps a little explanation of that would be helpful. For example, the different versions of jquery (your jquery script may require different version than the wordpress’) and where to add it (header or footer which is determined by the true/false parameter). The jquery script needs to be added in the header, (hence a ’false’ needs to be passed as the param value), otherwise it may not work.

  4. Hansjörg Leichsenring says

    There are often a lot of style.css.
    How can I ensure the correct load-order with enque and make sure, that the child css is loaded last?

    Cheers from Germany
    Hansjörg

  5. Carlos Araya says

    How do I pass empty parameter to register_script? I want to make sure that they script is loaded at the bottom of the page but can’t find information whether this is the default behavior or not

    • Kerry Beeher says

      Bonjour,

      Thank you for your excellente resource. Merci !!!

      I am little novice and just begin my journey to learn PHP and how WordPress use wp_enqueue_script and wp_register_script to add JavaScript and CSS.

      I use this free plugin called Easy Code Manager to help run through your exemples:
      however I am not sure if this is right plugin to use.

      I read before that it is not the best idea to modifier code in functions.php so I wonder if this is ok to do?

      Will it not get change on a theme update?
      Sorry for question, I still learn WordPress.

      Merci,
      Kerry

  6. Vaibhav Bansal says

    I want to add an Amazon Ad
    I tried to add it in text widget, but it shows blank.
    Below is the code-

    This is my site-
    Help me. How do I add js on my site?

  7. pradyumna says

    i have inserted a javascript using this plugin but now i have to remove it, i have tried uninstalling and deactivating the plugin but the javascript still executes

  8. Vijay.Rajpal says

    Hello Sir,
    I am using esteem theme and I wanted to add some javascripts functionality to my website like lightbox. I have created a child theme and the code are as follows. in the functions.php.

    and I am getting an error:-Parse error: syntax error, unexpected '{' in E:\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-content\themes\esteem-child\functions.php on line 18
    Please Help I am using sublime as my text editor.
    Please Help!!!!!

  9. Pramod says

    hello…..
    i m adding .js file in js directory of wordpress and gives its reference of it in funcation.php
    but its not working

    wp_enqueue_script( ’any-navigation’, get_template_directory_uri() . ’/js/menu.js’);

  10. Bobbie says

    Thanks so much! I’ve been trying to add a custom .js file but this is the first explanation that the register_script was needed.

  11. colkav says

    Hey, great tutorial. I’m having an issue adding a Google Analytics related javascript, as described here:
    I’ve put the script in my child theme’s ’js’ folder (having first stripped the html from the code).

    When i load up the page I keep getting the error :

    ReferenceError: Can’t find variable: ga
    (anonymous function)myscript.js:6

    …and it just dawned on me that maybe I need to add ’analytics.js’ as a dependency!

    Does that sounds right? And if so, how would I add analytics as a dependency for my script? I’ve tried experimenting here to no avail :(

  12. xavi says

    Hi.
    thanks for this amazing post tutorial! But when you say ”where to upload the script” you just can define head or footer (in all entire webpages!)? Could you define an especific page to load it? I just need it in one. Thanks for advance and keep working! Cheers.

  13. Skye Barcus says

    I am a total novice at js but do know html. I want to put this on a wordpress page:

    Basically, it’s a widget to join a GoToMeeting. This works if you just throw it into the body of an html page, but in WordPress, it gets supressed.
    Can you give me a ”For Dummies” version of how to make this work?

  14. Dejan says

    I really like you site it is full of useful tips, however looks like you are not doing it ”Properly” for CSS enqueue even though your title say that way :=) The right way would be :

    wp_register_style( ’my-css-style’, get_template_directory_uri() . ’/css/style.css’, array(), ’1.0’, ’all’ );
    wp_enqueue_style( ’my-css-style’ );

    Keep up the good work… Cheers!

  15. Adrian Zumbrunnen says

    Thanks for the effort you put into this. It just feels wrong to have wp_enque_script for loading stylesheets. WordPress could eventually spit out script instead of the stylehseet syntax for it.

    Do you really embed that way?

    • WPBeginner Support says

      This tutorial shows how to load JavaScript and stylesheet files for your themes or plugins in WordPress. If by Embed you meant how we display code in articles, then we use Syntax Highlighter plugin for that.

      Administratör

  16. oiveros says

    hi i’m kind of new on the wordpress theming , and reading about these topic, i wanted to ask you about something related to these . If i want to update the jquery library link how do i do it or where do i find the link i been trying to do it but i can’t find it. Thank you in advanced for your help

    • WPBeginner Support says

      If by updating jquery library link, you mean to add jquery from Google’s library. WordPress comes packed with jquery and to load it in your theme use this line in your theme:

      <?php wp_enqueue_script('jquery'); ?>

      Administratör

      • oiveros says

        okey so if i want to have the latest jquery, i just use that line?, because somebody told me to use a plugin just for that, but i wanted to learn how to do it without a plugin

        • oliveros says

          Thank you for your answer, i found the post related to that issue here in your site.

  17. Elliott Richmond says

    Useful Syed, thanks.
    I recently had an issue loading a css file using _underscore as a framework, although the stylesheet was called mycustomstyles.css the theme was calling mycustomstyles.css?ver=xx and the theme wasn’t loading the file because of the naming of the file by appending ?ver=xx to the end of the name.
    Is that something to do with $ver default?

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.