{"id":9353,"date":"2016-08-11T05:09:22","date_gmt":"2016-08-11T09:09:22","guid":{"rendered":"http:\/\/byteplate.com\/uncategorized\/javascript-for-wordpress-developers-loading-javascript-in-wordpress\/"},"modified":"2016-08-11T05:09:22","modified_gmt":"2016-08-11T09:09:22","slug":"javascript-for-wordpress-developers-loading-javascript-in-wordpress","status":"publish","type":"post","link":"https:\/\/byteplate.com\/wpmu-dev\/javascript-for-wordpress-developers-loading-javascript-in-wordpress\/","title":{"rendered":"JavaScript for WordPress Developers: Loading JavaScript in WordPress"},"content":{"rendered":"<p>Over the past three weeks, we\u2019ve looked at how\u00a0to get started using JavaScript on your website, how to implement jQuery for animations and effects, and how to use JavaScript objects as part of this series.<\/p>\n<p>Now we\u2019re going back to basics. In order to actually use JavaScript, you need to know how to load it onto your site.<\/p>\n<p>This is the fourth post in our five-part series focusing on JavaScript for WordPress developers. Throughout this series, you\u2019ll learn the basics, but I\u2019ll presume you already have a working knowledge of HTML and CSS. If you need help with these building blocks, take a look at our series about <a href=\"https:\/\/premium.wpmudev.org\/blog\/wordpress-development-beginners-getting-started\/\">WordPress Development for Beginners<\/a>.<\/p>\n<p>So far in this series we\u2019ve looked at the basics of JavaScript, variables, arrays, functions, objects and we\u2019ve sunk our teeth into basic jQuery. Now it\u2019s time to dig a little deeper and start to understand how jQuery fits together with WordPress and how you can load scripts while maintaining their dependencies.<span id=\"more-157288\"><\/span><\/p>\n<h3>How WordPress Loads Scripts<\/h3>\n<p>Let\u2019s take a step back and first look at how WordPress loads scripts and styles. We\u2019ve learned that when creating JavaScript files you can add them to your page in the head section or in the body section, preferably at the bottom.<\/p>\n<p>WordPress does the exact same thing but you can\u2019t (read: shouldn\u2019t) just plop these script tags in the header or footer file of your theme. WordPress uses an intelligent loading mechanism called <strong>enqueueing<\/strong>\u00a0that figures out which files to load and when.<\/p>\n<p>This mechanism is needed to make sense of dependencies. If you write some jQuery code for your theme, jQuery itself needs to be loaded first. You may write code that relies on a jQuery plugin. In this case, jQuery must be loaded first, then the plugin, and then your code.<\/p>\n<h3>Enqueueing Scripts<\/h3>\n<p>You can enqueue scripts in your theme\u2019s functions file or in a plugin file. Here\u2019s the full code for including a script that relies on jQuery:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>Firstly, a function must be hooked into WordPress. The first argument of the <code>add_action()<\/code> function tells WordPress where these scripts should be placed: in the front-end of the website or in the admin. If you use <code>wp_enqueue_scripts<\/code> they will be placed on the user-facing side, if you use <code>admin_enqueue_scripts<\/code> they will be placed in the admin.<\/p>\n<p>Within the hooked function you can use <code>wp_enqueue_script<\/code> to add the scripts you need. The function takes one required and four optional parameters:<\/p>\n<ol>\n<li>The first parameter is the name of your script. You can choose any you like but make sure to name it something unique to prevent naming issues.<\/li>\n<li>The second parameter should contain the location of the script file.<\/li>\n<li>The third parameter contains an array of dependencies. In the example above I\u2019ve indicated that jQuery is a dependency. All dependencies are loaded before the script.<\/li>\n<li>The fourth parameter is a version number<\/li>\n<li>The fifth and final parameter indicates whether you want to load the script in the header or at the very end of the body section. Use <code>true<\/code> to load at the end, or <code>false<\/code> (or omit the value) to load it in the head section.<\/li>\n<\/ol>\n<h4>Dependencies<\/h4>\n<p>WordPress ships with a copy of jQuery, which is why you can add it as a dependency without any hassle. There are a great many other scripts and jQuery plugins WordPress contains. If your code depends on any of them don\u2019t include your own copy, just add it as a dependency. See this <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/wp_enqueue_script\/#defaults\">script list<\/a> in the WordPress Codex to see which ones you can use.<\/p>\n<p>If you are including multiple scripts of your own making you can add them as dependencies just the same. Take a look at the example below:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>Note that since the base script depends on jQuery the extension script depends on it as well. Regardless, you do not need to add jQuery as a dependency for both. This makes script management a lot easier!<\/p>\n<h4>Registering &amp; Enqueueing<\/h4>\n<p>Adding a script actually consists of two steps but if you use the <code>wp_enqueue_script()<\/code> as shown it is condensed into one. In reality, the first is registered with WordPress, which means that WordPress will \u201cknow\u201d about the script. The second step is enqueueing when it is actually added to the page.<\/p>\n<p>In some cases you may want to do them separately to ensure efficient loading of scripts. I\u2019ll show you some neat use-cases shortly.<\/p>\n<p>To register and enqueue in two steps simply use the <code>wp_register_script()<\/code> with the exact same parameters as you used <code>wp_enqueue_script()<\/code>, then use <code>wp_enqueue_script()<\/code> with a single parameter, the script name (sometimes called the handle.)<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>If you\u2019re registering and enqueueing in the same place it doesn\u2019t really make sense but as you\u2019ll see in a moment, sometimes you can register in one function and enqueue in another.<\/p>\n<\/div>\n<p><!-- end container --><\/p>\n<div class=\"full-blogad full-blogad-courses\" id=\"full-blogad-156655\">\n<div class=\"full-blogad-container\">\n<div class=\"row\">\n<div class=\"col-sm-24 col-md-11 col-md-offset-1\">\n<h3>COURSES<\/h3>\n<h4>WP Academy \u2013 WordPress Wisdom, Bitesized.<\/h4>\n<p>Structured e-learning to expand your WordPress and general business horizons. Learn from people like our very own CEO James Farmer with more than a decade\u2019s experience running a WordPress Business!.<\/p>\n<p>  <a href=\"https:\/\/premium.wpmudev.org\/academy\" class=\"ghost-button-arrow i-wpmudev-tail-arrow open-trial\">LEARN MORE<\/a>\n<\/div>\n<div class=\"col-sm-24 col-md-10 col-md-offset-2\">\n  <img decoding=\"async\" src=\"https:\/\/premium.wpmudev.org\/wp-content\/themes\/wpmudev-2015-1\/assets\/img\/trial\/courses.svg\">\n<\/div>\n<\/div>\n<p><!-- end row --><\/div>\n<p><!-- end full-blogad-container --><\/div>\n<p><!-- end full-blogad --><\/p>\n<div class=\"container\">\n<h4>Conditional Loading<\/h4>\n<p>Sometimes you\u2019ll want to use your script on every single page but often you only need it in specific places. This is especially true when creating scripts for the admin. A good example is the use of shortcodes. Shortcodes enable users to create advanced displays in the content editor using a few simple tricks.<\/p>\n<p>For example, you could build an image carousel which users could add to the post like this: <code>[carousel ids='42,124,123,331,90']<\/code>. A carousel would be created on the post\u2019s page using the images designated by the ids. To make this happen you would create <code>carousel.js<\/code> which relies on jQuery. Here\u2019s some code to make this happen (it won\u2019t actually make the carousel just demonstrate script loading):<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>We registered the script to make sure WordPress knows about it, but we only enqueue it within the shortcode function itself. This way the script is only added to the page if the shortcode is used on the page. Neat-o!<\/p>\n<p>Another method to load scripts conditionally is the use of conditional functions. If you want to load a script on all category archive pages you could use the <code>is_category()<\/code> conditional tag.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The WordPress Codex entry on <a href=\"https:\/\/codex.wordpress.org\/Plugin_API\/Action_Reference\/admin_enqueue_scripts\">admin_enqueue_scripts<\/a>\u00a0offers a great example of how to target scripts to specific admin pages.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The first parameter of the hooked function is the id of the page you are on currently. In the example above, whenever that id is not <code>edit.php<\/code> the function simply returns. Otherwise it enqueues the script.<\/p>\n<h3>Removing and Replacing Scripts<\/h3>\n<p>This is by far a common scenario but every once in a while you may need to remove or replace a script. I\u2019ve bumped into situations where a script added by a plugin (but not used by the theme) caused issues. Removing it was the best option, it made the error disappear right away.<\/p>\n<p>You may also want to replace jQuery with a newer version if you\u2019re testing something to make sure it will be compatible with newer versions.<\/p>\n<p>These situations are where <code>wp_deregister_script()<\/code> and <code>wp_dequeue_script()<\/code> come in handy. Here\u2019s how to replace WordPress\u2019 built-in jQuery with your own:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<h3>Final Thoughts<\/h3>\n<p>The enqueuing method within WordPress is great because it allows you to add your scripts modularly. You can always be sure that dependencies will be loaded properly \u2013 you don\u2019t even need to supply many of them since WordPress is full of jQuery plugins.<\/p>\n<p>If you\u2019re working with styles you can enqueue and register them in the same way, just use <code>wp_enqueue_style()<\/code>. Finally, make sure not to litter your plugin or theme with scripts. You should use as few as possible and concatenate them into one file if it makes sense.<\/p>\n<p>In the next tutorial\u00a0in this series, we\u2019ll take a look at how to use AJAX to add some great functionality to your WordPress\u00a0site.<\/p>\n<div class='yarpp-related-rss'>\n<p>Related posts:<\/p>\n<ol>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/adding-scripts-and-styles-wordpress-enqueueing\/\" rel=\"bookmark\" title=\"Adding Scripts and Styles to WordPress the Right Way With Enqueueing\">Adding Scripts and Styles to WordPress the Right Way With Enqueueing <\/a> <small>Many of us use styles to alter the look of&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-wordpress-objects\/\" rel=\"bookmark\" title=\"JavaScript for WordPress Developers: Getting Started With Objects\">JavaScript for WordPress Developers: Getting Started With Objects <\/a> <small>Objects are one of the most important and most powerful&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/getting-started-jquery\/\" rel=\"bookmark\" title=\"JavaScript for WordPress Developers: Getting Started With jQuery\">JavaScript for WordPress Developers: Getting Started With jQuery <\/a> <small>jQuery is a popular open source JavaScript library that enables&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-wordpress-basics\/\" rel=\"bookmark\" title=\"JavaScript for WordPress Developers: Learning the Basics\">JavaScript for WordPress Developers: Learning the Basics <\/a> <small>JavaScript was developed over 20 years ago at Netscape and&#8230;<\/small><\/li>\n<\/ol>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Over the past three weeks, we\u2019ve looked at how\u00a0to get started using JavaScript on your website, how to implement jQuery for animations and effects, and how to use JavaScript objects as part of this series. Now we\u2019re going back to basics. In order to actually use JavaScript, you need to know how to load it onto your site. This is &#8230; <\/p>\n<div><a href=\"https:\/\/byteplate.com\/wpmu-dev\/javascript-for-wordpress-developers-loading-javascript-in-wordpress\/\" class=\"more-link\">Read More<\/a><\/div>\n","protected":false},"author":1,"featured_media":6903,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[141],"tags":[236,251,124,136],"class_list":["post-9353","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-wpmu-dev","tag-development","tag-javascript","tag-wordpress","tag-wpmu"],"acf":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/a-b\/bg-man-and-woman-on-ipad.jpg?fit=1600%2C1068&ssl=1","jetpack_shortlink":"https:\/\/wp.me\/p6EepC-2qR","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts\/9353","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/comments?post=9353"}],"version-history":[{"count":0,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts\/9353\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/media\/6903"}],"wp:attachment":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/media?parent=9353"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/categories?post=9353"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/tags?post=9353"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}