Blog posts under the development tips tag https://webdevstudios.com/tags/development-tips/ WordPress Design and Development Agency Mon, 15 Apr 2024 16:02:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the development tips tag https://webdevstudios.com/tags/development-tips/ 32 32 58379230 Quick Tip: How To Disable Next.js Telemetry https://webdevstudios.com/2021/09/09/quick-tip-how-to-disable-next-js-telemetry/ https://webdevstudios.com/2021/09/09/quick-tip-how-to-disable-next-js-telemetry/#respond Thu, 09 Sep 2021 16:00:41 +0000 https://webdevstudios.com/?p=24252 Want to stop Next.js telemetry? Here is a quick tip. You can disable it via the command line or via the environment file. If you are looking only at the command, you can skip this background information section and scroll to the disable section. According to the Next.js team, they collect telemetry data to improve Read More Quick Tip: How To Disable Next.js Telemetry

The post Quick Tip: How To Disable Next.js Telemetry appeared first on WebDevStudios.

]]>
Want to stop Next.js telemetry? Here is a quick tip. You can disable it via the command line or via the environment file.

If you are looking only at the command, you can skip this background information section and scroll to the disable section. According to the Next.js team, they collect telemetry data to improve the developer experience and to ensure its growth. This makes it easier for them to find where the users get stuck and the possible areas to improve. Also, they have mentioned that their manual improvement process slowed down the growth of Next.js.

Let’s begin by looking at what telemetry is. Telemetry is the automatic collection of data to a remote system. It helps to get more information about the environment and to access the performance.

This differs slightly from users reporting bugs and feedback. As the configuration differs for every user, telemetry helps to understand the users’ needs better.

Next.js Telemetry

Enough of the backstory. Let’s see what data is being collected.

  • Next.js version and installed Next.js plugins
  • Environment information (operating system, continuous integration is enabled or not, number of CPUs)
  • Number of pages in the app
  • How long it takes to build (on the next build command)
  • Commands used (next dev, next export, or next build)

Debugging Telemetry Data

As a developer, you would like to see what Next.js collects, just like me.

You can debug telemetry data by adding NEXT_TELEMETRY_DEBUG=1 in your .env file. This allows you to check what data is being captured by telemetry. In debug mode, it doesn’t send data just outputs in the console.

For a quick demo, I’ve got this telemetry output from my existing Next.js app.

Next.js Telemetry Debug Info

Whoa, that’s a lot of information to me! It does not contain any sensitive information like file paths, errors, logs, and environment variables.

Disabling Telemetry

By default, telemetry is enabled. That means you can opt out if you don’t want to share any data. It should be the other way around (I get what you’re thinking!).

To disable telemetry, you can add NEXT_TELEMETRY_DISABLED=1 to your .env file.

You can also run the command npx next telemetry disable in the root of your project directory.

Make sure that it is disabled by checking the telemetry status.

Next.js Telemetry Check Status - Disable

That did the trick! For more information, visit Next.js official documentation page.

Did you find this quick tip useful? We’ve got a ton of valuable information on Next.js. Read our Headless CMS tutorials. 

The post Quick Tip: How To Disable Next.js Telemetry appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/09/09/quick-tip-how-to-disable-next-js-telemetry/feed/ 0 24252
Best Practices for WordPress Website Image Optimization https://webdevstudios.com/2018/08/16/wordpress-website-image-optimization/ https://webdevstudios.com/2018/08/16/wordpress-website-image-optimization/#comments Thu, 16 Aug 2018 16:00:24 +0000 https://webdevstudios.com/?p=18963 The most significant consideration for building or maintaining a website these days is speed. Ensuring that your site moves quickly and supports speeds down to mobile 3G is vital in providing the best possible user experience (UX) to the largest percentage of your target demographic. The guiltiest speed hogs are network requests dedicated to fetching Read More Best Practices for WordPress Website Image Optimization

The post Best Practices for WordPress Website Image Optimization appeared first on WebDevStudios.

]]>
The most significant consideration for building or maintaining a website these days is speed. Ensuring that your site moves quickly and supports speeds down to mobile 3G is vital in providing the best possible user experience (UX) to the largest percentage of your target demographic. The guiltiest speed hogs are network requests dedicated to fetching images and video media. One of the best ways to improve UX and guarantee site speed is to consistently practice techniques for WordPress website image optimization. If you think about images as a percentage of your overall website’s footprint, a few bytes here and there will certainly add up. By optimizing images, you can reduce the overall impact of your website’s footprint, page size, and increase load speeds.

Image optimization is just that, optimizing, compressing, scaling, resizing, or changing image formats for the web. The general idea is to reduce how many requests you have to make or how large those requests are in the first place. Google uses a term called “time to first meaningful paint,” which is when “the user feels that the primary content of the page is visible.”  The faster users get to the information they’re looking for, the better off you will be.

There are many ways that WordPress website owners can improve load speeds. Some techniques can be used before an image makes it to your website and some by directly modifying your server configuration and the way that the site handles images. Let’s explore both.

Compression and Optimization

Uncompressed images can contain additional bulk that should be removed when you save your files for the web, once you already have an image, or once it’s already on your website. You can manually optimize images in programs like Photoshop, Pixelmator, or Affinity Photo. By ensuring that you’re selecting the proper image format, quality, and a few other settings, you’ll be well on your way to improving your website. Photoshop, for example, has a default preset called “JPEG High” that takes care of the bulk of the optimization for you which is probably a safe bet nine times out of ten.

We want to make sure that our image quality is set as low as possible without destroying the integrity of the image. Select “Optimized” to strip out unnecessary data from the image and further compress it. I typically find that 60 is a good quality. Much lower than that and you’ll start to see major image degradation.

A slight note on quality: by default, WordPress uses the jpeg_quality hook to set uploaded JPEG/JPG image quality to 60. You may find that images that seemed clear initially are a little fuzzy after upload. So, play around with the quality vs size ratios to see what works best for you.

JPG vs PNG vs All the Other Formats

JPG/JPEG and PNG are by far the most popular image formats you’ll see online. There are plenty of other image formats like GIFs and newer formats like JPEG 2000, JPEG XR, APNG, but you don’t need to worry about all that. Most of them aren’t widely supported by major browsers or don’t provide any additional benefit. So if you see those online, stick to the basics.

JPG/JPEGs are “lossy,” meaning that unnecessary data is removed during compression or when you save a file as a JPEG. Most of the time this doesn’t matter especially for photos, but if your image has text in it or requires transparency, you might be better served with a PNG.

PNGs support transparency and have a higher level of quality because they’re considered “lossless,” which means that no data is lost during compression. Graphics with details, like text, or that require transparent backgrounds/elements are perfect for a PNG. However, because none of that information is removed or lost, it will end up being a larger file than a JPEG. Play around with those formats and see. Sometimes the difference in size is negligible, and sometimes you’ll see a PNG at two or three times the size of a comparable JPEG.

So which is right for you?

If you’re saving an image to be a background element, design element, photograph, or something that doesn’t need to render super-detailed elements, JPEG is the way to go. If you’re dealing with text over images, transparency, or need super-detailed or crisp edges, a PNG is the way to go.

What about SVGs?

Keep in mind that not everything needs to be an image. SVGs are super lightweight because they are generated by mathematically rendering shapes from just a few lines of text. SVG supports transparency, animation, and can be colored programmatically unlike raster images. SVGs, because they are vector shapes, can be as large or as small as you want without ever losing quality.

Not everything can be an SVG, though. Only elements that don’t rely on pixels (photographs) can be an SVG. Simple icons and shapes or your logo are prime examples of an SVG use case. Because it’s code rendered by your browser, it’s super lightweight and doesn’t bog down your server with beefy network requests.

Size

I’m not necessarily talking about file size here. If we’ve optimized our images properly and chosen the right file format, we should be in good shape as the file size is concerned. I’m talking about the dimensions of the image. If the image you’re using will take up approximately 300 pixels x 200 pixels on screen, you don’t need to be using an image that is ten times the size, which happens more often than you’d think. Website platforms like WordPress will automatically generate many different sizes to allow users to select a more reasonable image size instead of always embedding “full size” images.

Purposefully selecting images and image sizes for sections of your website is vital toward improving your website’s performance. If you don’t have a desktop program, there are plenty of websites online to help you out like Image Resize or Pixlr Editor with similar size and optimization capabilities.

Metadata

All image formats contain additional metadata by default—data that describes the file, such as a title, copyright information, image ratings, GPS location data, file and dimension sizes, how, where, or when the file was edited, etc. Most of the time, these are necessary for the web unless you’re protecting your property intellectually, but that’s for another day.

Selecting the “optimized” function in Photoshop, or selecting “None” in the Metadata dropdown, will further reduce your file sizes. It is often helpful when the image is only intended to be used as a design element, or your source attributions are coded into the website itself.

Scale Images and Retina Devices

You want to select the right image for the job, but you also want to make sure that you’re providing some flexibility for desktop, tablet, and mobile devices just the same. A desktop website view might have an image of 600 pixels x 800 pixels in size, but for a phone that might be overkill, especially on slower internet speeds or older phones.

WordPress provides the ability to display images for each browser size dynamically using the `srcset` property of an image. So the image that is loaded on mobile devices is different from the image on tablet or desktop devices. They are incrementally smaller to ensure a faster load time, all handled within the image call dynamically for you.

Apple devices and devices with higher DPI screens tend to expect higher quality images in order to render clearly. The general rule is to serve images up to two times the maximum display size on all devices—desktop, tablet, and mobile at 600 pixels x 400 pixels, 400 pixels x 300 pixels, or 300 pixels x 200 pixels, respectively. Make sure that all images are optimized for the device, but also not larger than the maximum use case.

As long as you never use an image that’s larger than you need, you should be a-okay. Imsanity, a plugin for WordPress, also provides the ability bulk size or resize images for your browser more efficiently, rather than having to update your theme or configure any servers.

Caching

If you’re running any site audit tool, you might see “Leverage Browser Caching” come up as something to address. Storing images within the browser to quickly grab and render when your website loads, instead of having to make a network request to retrieve it, will reduce the load times and page size exponentially. Browser caching is a bit more complicated or may require an engineer to help optimize as it typically needs a server configuration to handle Cache-Control headers and Expires headers.

If your images don’t change very frequently, or at all, caching your media would provide almost instant access to your assets without needing to make a full network request every time, and websites that continually changes or doesn’t get high volume traffic may not necessarily benefit much from this approach. Plugins like Leverage Browser Caching may provide a direct ability to edit your headers but should be used with caution. Keep in mind, that this plugin is only intended for use with Apache Servers. Several hosting companies out there rely on NGINX, like WPEngine, so this would require a more dev-centered-server-configuration approach.

Also remember, however, that when caching is enabled you may be continuously needing to ask your users or clients to “flush their caches” or need to flush site caches manually.

CDN

A Content Delivery Network (CDN) allows you to store cached content which serves up content directly to your users rather than waiting for requests from your website instantly. A CDN’s obvious benefit is speed for all users no matter where they might be on the planet. A CDN provides proxy servers with your content for quick and reliable access regardless of location. Without a CDN, a server in New York, for example, would load much faster to someone in Ohio than it would to someone in New Zealand. With a CDN, those proxy servers relay information based on location to ensure speed.

CDNs, along with speed and caching, provide additional security benefits which are especially helpful if your content is in any way sensitive.

Additional Services

There are many other services out there to help optimize images or serve them up more efficiently. Two good examples are Smush Image Compression and Kraken Image Optimizer. Both are paid services that allow you to compress and optimizes images already in your WordPress media library, as well as those uploaded thereafter.

For optimization on-the-fly, there is Cloudinary, which allows you to upload, manage, optimize, and store images. Images are delivered via CDN and provide responsive assets as needed automatically. Cloudinary also allows you to modify, define image sizes, add effects, or change alignment on-the-fly by using URL query string options, which is a nice additional feature but not always necessarily related to image optimization.

Don’t Forget the Frontend

I’ve been talking about image optimization in a technical sense, but we can also think about optimization in the sense that organizing images, calling them correctly, and using best practices for the web can improve website visibility for SEO and avoid potential accessibility pitfalls. Ensure all images have unique alt text, something that is almost always neglected in my experience but is one of the more critical aspects for accessibility and SEO.

All unique file names should then have unique alt text. If an image is decorative, the proper way to present them is as a background image in your CSS, but if it must be inline and is purely decorative, it should at least define the alt tag as empty with the role attribute of presentation.

<img role="presentation" alt="" />

An alt tag should directly reference the image that is being displayed. If an image src is broken or unavailable, or a visually impaired individual is using your website, they should know what they’re looking at by its description. image-1 is an unacceptable alt text.

If you find yourself needing to provide an additional explanation about the image, you may use the longdesc="" attribute and give a location or file for reference, which is helpful for diagrams, etc.

Summation

It’s not the easiest thing in the world to assess and optimize your media, but you will find that once you do, your users will thank you by staying on your website longer. After all, a large percentage of website visitors will up and leave if they don’t get the information they need from in under three seconds. That alone makes WordPress website image optimization worth the effort. However, if you still need help, contact us for assistance.

The post Best Practices for WordPress Website Image Optimization appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2018/08/16/wordpress-website-image-optimization/feed/ 2 18963
The Importance of QA and UAT https://webdevstudios.com/2017/07/11/importance-qa-user-acceptance-testing-project/ https://webdevstudios.com/2017/07/11/importance-qa-user-acceptance-testing-project/#respond Tue, 11 Jul 2017 16:00:25 +0000 https://webdevstudios.com/?p=17233 We all have pride. Whether that pride comes from our career or what we create outside of work, we all have a sense of pride in something. In web development, it is critical to balance personal pride in your work with taking constructive criticism about your creations. After dedicating a great deal of time and energy into developing a website, it can Read More The Importance of QA and UAT

The post The Importance of QA and UAT appeared first on WebDevStudios.

]]>
We all have pride. Whether that pride comes from our career or what we create outside of work, we all have a sense of pride in something. In web development, it is critical to balance personal pride in your work with taking constructive criticism about your creations. After dedicating a great deal of time and energy into developing a website, it can be difficult to receive not-so-positive feedback from your peers. However, two essential parts of website development is quality assurance (QA) and user acceptance testing (UAT), which means you have to be prepared to manage and even incorporate constructive criticism and feedback.

QA and UAT are review processes that are done during a web development project to ensure design and functionality requirements are met prior to a production release.

When you spend weeks, or even months, on a project only to wind up with a handful of QA issues (that you should have caught the first time around), it is easy to feel discouraged. You can receive QA feedback for scenarios you did not even think about the first time around. The person performing QA isn’t intending to discourage the developers. QA and UAT are intended to find the obvious issues, and the most nit-picky annoying ones that no one thought to test.

The goal of QA and UAT is to break the site… the code.

Self-QA

A major part of the QA process during development is doing it yourself. Remember that you, as the developer, are responsible for being the first set of eyes reviewing your code. Unfortunately, you can code a feature for so long that you become blind to obvious issues.

Slow down. We do have deadlines to meet, but a quick break from your code can really help. Taking a lunch break, stepping away from the screen for a few minutes, or even working on another task for a bit can get you refreshed for self-QA. You’ll be able to see the little things you can clean up, fix, or completely change for clarity, because you’ve taken a quick break from your code.

Another method of self-QA is to take the feedback you received at the end of your last project and apply it to new code. Do you consistently receive the same feedback on issues when a formal QA is done? If so, keep track of that feedback and include it as part of your initial development.

Peer Review

When you need a second pair of eyes, use your peers. If you’re building a large feature, using a new skill set, or just want some additional feedback on a task before turning it in for final review, grab a peer to review your code. If you’re working with a team, lean on them to make your code better and expect them to do the same with you. We should all have the same goal, produce the best possible product by writing the best possible code. 

Here at WebDevStudios, we have a system in place for our peer reviews. A developer will work on a feature and pass it to a senior developer for the initial round of code review. If everything passes their checklist, they pass it onto the a lead developer for final review and scrutiny.

A senior or lead developer may not have all the skills to get your code up to par. This industry changes so rapidly that no single developer can truly know everything. If you see code that a senior or lead developer can improve upon, let them know; and hope that you work in an environment, like WebDevStudios, that encourages knowledge sharing.

Formal QA and UAT

Once self-QA and peer review has been completed on individual tasks within a project, it’s time to do a full project QA and UAT review. This process will most likely be unique to your company or team structure. The general process is that an individual, or team of developers, reviews the entire site to perform visual and functional QA.

Visual QA and functional UAT processes may be completely separate from one another. Comparing a page in the browser to the mock-up, and running through a specific set of functionality, like new user registration, are two entirely different things. It is critical to perform both QA visual review and functional UAT.

As a freelancer or company, you also need to define your own pass/fail scenarios on visual QA. Do you want to strive for absolute pixel perfection, or is it okay for the placement of something to be off by two pixels? Will it be important to the client to take the time to take screenshots, write up a task, have it assigned out, worked on, and finally reviewed?

What isn’t subjective, though, is whether or not a thing actually works. This is where a strong-handed UAT comes into play. Before you can have a solid UAT process, you need to have a solid process for documenting how something should work. This can be either with user stories defined by the client in the project plan itself, or documentation written as the project progresses. If user stories are in place from the beginning, that means each developer knows exactly what they need to do in order to complete their work. Providing user stories can be a major cornerstone along the QA and UAT process.

Client QA

Once an internal formal QA and UAT is completed, it’s time to hand off the completed project/site to the client so they can run through their review and testing process. Each client is unique and will have their own QA and UAT review processes to ensure their site is functioning as expected, per the proposal, prior to a production release.

Clients are typically able to find bugs when they run their QA. Clients have very specific ideas about how things should look, function, and how they should be able to interact with elements on the site. Certain features or functionality may not have been conveyed in static mock-ups. For example, the way images or links hover, or how unique sets of content resize for small screens. This is where user stories can help to eliminate some of that disconnect between static mock-ups, and a fully functioning website. When clients find bugs or issues based on expected functionality, we consider this a learning experience. We have the opportunity to improve our processes so that we can improve on assumptions for the next project.

Conclusion

There are so many methodologies around what we do and how to do it more efficiently – whether it’s making sure your code is as clean as possible, or that your functions do just one thing. These are hallmarks of being a solid developer. But, if you’re writing clean, smart code and testing it in different scenarios, you’ll wind up with fewer issues in the various stages of QA down the line.

QA is not a single process run at the end of a project. In reality, QA happens at several points along the way, starting with the developer working on the task and performing self-QA, peer reviews with senior and lead developers, onto the person running internal QA, and finally in the client’s hands. The earlier an issue is caught, the better it is for everyone along the path of review. It’s so important to be able to reflect on your previous projects and apply the knowledge you’ve learned at the earliest stage possible.

What are your methods for QA-ing your work on a site from start to finish? Do you have suggestions or tips on how others could possibly benefit from your own workflows? If so, share them in the comments and let us know!

The post The Importance of QA and UAT appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/07/11/importance-qa-user-acceptance-testing-project/feed/ 0 17233
Accessibility of Semantics: How Writing Semantic HTML Can Help Accessibility https://webdevstudios.com/2017/05/23/accessibility-semantics-writing-semantic-html-can-help-accessibility/ https://webdevstudios.com/2017/05/23/accessibility-semantics-writing-semantic-html-can-help-accessibility/#respond Tue, 23 May 2017 16:00:42 +0000 https://webdevstudios.com/?p=13941 Writing HTML is about more than simply “having stuff appear on the page.” Each element you use has a meaning and conveys information to your visitors, especially to those that use assistive technologies to help interpret that meaning for them. A majority of a site’s visitors will be able to use their sight to help Read More Accessibility of Semantics: How Writing Semantic HTML Can Help Accessibility

The post Accessibility of Semantics: How Writing Semantic HTML Can Help Accessibility appeared first on WebDevStudios.

]]>
Writing HTML is about more than simply “having stuff appear on the page.” Each element you use has a meaning and conveys information to your visitors, especially to those that use assistive technologies to help interpret that meaning for them.

A majority of a site’s visitors will be able to use their sight to help them understand what things are and what they might do. For them, it’s largely irrelevant that the thing that looks like a button isn’t built with a <button> element. As long as it functions in a way that matches their goals and expectations, they will be happy (maybe even delighted if it does exceptionally well).

But what if you couldn’t see the page for yourself and you need assistive technology to help you? Suddenly, all the inherent semantic information that HTML elements carry becomes infinitely more relevant.

This post will describe three examples where semantics matter and how they may influence a user’s experience on the website.

Anchors, and buttons, and spans, oh my.

It’s entirely possible to add a span or a div to a page, slap some CSS and JS on it, and call it a button. Maybe you’d do it because it’s “easier” to make it look like the design that way. Or, maybe you have a different reason for doing this. However, you’d only be doing yourself a disservice by reinventing the wheel and making a bunch of extra work for yourself.

You see, it may look like a button. It may even act like a button when you click it. What it most likely won’t do is get added to the page’s list of focusable elements. This means that people navigating your site with a keyboard will never be able to reach it, let alone interact with it.

And, I can almost guarantee that it won’t identify as a button either. This is an important detail to those that use assistive technologies to tell them what something is. If I don’t even know it’s a button, then how can I be expected to know that I can interact with it?

Both of these shortcomings can be fixed to some extent, but why would you? The browser will take care of all of these things for you when you use the appropriate element, and it will do that much better than you can emulate them. As a bonus, you’ll be supporting older browsers without even trying!

In addition, both the anchor and button element have a number of additional attributes that are simply not valid to use with a div or a span – attributes with which you can give more information, or with which you can instruct the browser how to handle it.

For example, if I were to add the download attribute to a link, I can basically tell your browser to download the file I’m linking to instead of trying to open it. I can also add more information about the page I’m linking to through attributes like rel or hreflang.

Or, you can use the disabled attribute on a button element, which will allow you to easily disable it completely. A button that is disabled this way cannot get focus anymore, nor can it be activated anymore. For all intents and purposes, it does not exist anymore. Simply removing this state attribute will completely restore the button’s function again.

The subtle difference between anchors and buttons

A more common occurrence is anchor tags acting like buttons. While this isn’t necessarily as bad, you’d still be using an element whose primary function is relating documents (or sections of the same document) together to do something it wasn’t meant to do.

So how can you easily recognize when to use an anchor and when to use a button? If you are using a valid href attribute to link to a different page, or to a different section on the same page, then go right ahead and use an <a> tag.

Otherwise, every time you find yourself writing a toggle that is along the lines of one of the following, you may want to consider using a <button> instead:

<a href="#" id="click-this">Click Me, I do stuff</a>

<a href="javascript:toggleStuff();">No, click me. I do stuff too!</a>

Always remember, someone using a screen reader doesn’t really care what the thing looks like. All they will know is what their screen reader tells them about the thing, and that will come down to two simple words that carry a lot of implied meaning: “link” or “button.”

Headings, more than just text size

The headings (<h1><h6>) in your document provide for more than simply a way to increase the size of the text. It’s true that, visually, headings will stand out in most cases and do their job that way.

But remember, not everyone will be able to see your page. Headings have the added benefit of making an outline of your document available. They allow you to give a good overview of what the page is going to be about. Additionally, most screen readers allow their users to jump through the page from heading to heading. In this specific situation, your heading is now without any context and needs to convey what the section is going to be about by itself. And so, those sentences that are marked up with different heading levels become meaningless fractures.

For a good illustration of how navigating a page with headings works, have a look at this video:

Form elements

Forms, too, benefit from being structured semantically. Just like spans that were turned into buttons, your users will also stop liking you if you do not use form fields appropriately.

And like anchors and buttons, each form element (and especially more complicated ones, such as select boxes) come with inherent functionality based on the browser’s implementation. To stay on the select box example, this element lets you select an option with the arrow keys but will also allow you to select an option through typing. That is to say, typing “united s” in a list of countries will select “United States of America” for you. Screen readers will also read out every option as you navigate through the list with the arrow keys.

With all this in mind, it’s all the more heartbreaking to see form widgets that are aimed to replace these native elements for something that looks nicer or that has more functionality and do a poor job at it. It is really easy to forget about all the other things that these elements do for your users. And at the same time, it can be really complicated to get it to work well, too.

To illustrate, I’ve prepared a video straight from the demo page for one of these libraries that “enhances” form elements (it is irrelevant which one it is, really). It demonstrates how a regular select box element works in Chrome with NVDA running. As you’d expect, it reads out the options properly. The “enhanced” version, on the other hand, continuously reads out “blank,” at least until I try and filter the list by typing some letters, because then it starts repeating what I’ve typed instead.

But my feature needs some control that doesn’t even exist!

By now I can hear you think: “That’s great and all, but my needs surpass what native elements can provide.”

Awesome! By all means, use whatever elements you think are appropriate for your cool feature. But, don’t forget that you’re now responsible for making it accessible, too.

So, make sure you have a clear vision of the following:

  • What goal does it have and how does it do that better than other options?
  • How should it operate with a mouse?
  • How should it operate with a keyboard?
  • How does it manage focus states (which is especially important for more complicated widgets, like calendars, for example)?
  • What kind of feedback should it give the user?
  • And finally, what does it actually do when a user decides to use it?

And then make sure to read into WAI-ARIA, because this is exactly what a use-case WAI-ARIA is for.

Further Reading

The post Accessibility of Semantics: How Writing Semantic HTML Can Help Accessibility appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/05/23/accessibility-semantics-writing-semantic-html-can-help-accessibility/feed/ 0 13941
Accessibility in Chrome DevTools https://webdevstudios.com/2017/03/06/accessibility-chrome-devtools/ https://webdevstudios.com/2017/03/06/accessibility-chrome-devtools/#comments Mon, 06 Mar 2017 17:00:46 +0000 https://webdevstudios.com/?p=13850 Oh, the internet is a wondrous place – full of avenues to connect people, regardless of geography, language, or hardware. Accessibility is so broad and the usership is so diverse. When building a WordPress theme, I encourage you to think about the benefits of removing any potential barriers from someone being able to access information. Read More Accessibility in Chrome DevTools

The post Accessibility in Chrome DevTools appeared first on WebDevStudios.

]]>
Oh, the internet is a wondrous place – full of avenues to connect people, regardless of geography, language, or hardware.

Accessibility is so broad and the usership is so diverse. When building a WordPress theme, I encourage you to think about the benefits of removing any potential barriers from someone being able to access information. (Yay usability and inclusion!) As a reminder, the WordPress Accessibility Handbook is an excellent resource, which outlines minimum requirements you’ll need to meet in order to make your theme “accessibility-ready”.

There are several tools and resources out there that can assist in this process. Since my default browser is Chrome, I’d like to dive a bit deeper into how you can use Accessibility Developer Tools (a free extension from Google) to help out.

Note: “Accessibility” is often referred to as “a11y” and will be used interchangeably throughout this overview.

Running an a11y Audit:

Screenshop of Chrome Dev Tools 'Audit' tab with accessibility audit option availableSo, you’ve started to develop your WordPress theme and you want to check on how things are shaping up on the a11y side of things.

Once installed, you will want to select the “Audits” tab. In addition to the usual “Web Page Performance” and “Network Utilization”, there is now also an “Accessibility” option listed. By checking that option and running an audit (either for present state or on page reload, depending on preference), it will return a basic report from the current site.

The audit will (potentially) return a list from severe to passing of accessibility errors it calculated within your code. What is helpful about this is that it will show you the actual node in the DOM where this issue is taking place. It provides a link to the DevTools a11y wiki that relates to that issue, which in turn links you to the relevant area of the w3 spec.

Screenshop of Chrome Dev Tools 'Audit' tab with audit results listed

So much of accessibility documentation can seem quite dense and overwhelming. I know that for me, this really helps to break it down and give me a better idea of what should be happening within my code AND how to fix it.

Debugging Existing accessibility:

What if you’re trying to debug issues that have already been implemented that aren’t translating properly into actual functionality? Follow me once more to a magical place called “Accessibility Properties” that lives within your DevTools in the Elements panel. Just a note, depending on how your DevTools is laid out, it could be listed under the right-pointing double angle quotation mark ».

Screenshot of Chrome DevTools Existing Accessibility Properties List

Depending on which element you have selected, it will provide a list of properties that can help in validating ARIA roles/attributes and debugging colour issues, focus/visibility roles and text computation.

Focus and Visibility

This will list what is happening with tabindex and visibility. This is great to have consolidated in one place to double check properties. I’ve found it to be most helpful with elements like modals where something is focusable but behind other content and needs adjusting. Focus and visibility are two examples of things to be conscious when developing so people are able to navigate via keyboard. Again, remember to double check these and other WordPress standards as you’re developing your theme!

Colour Contrast

This will show you the current contrast ratio of your element. You will also see a suggested colour value pair to match the WCAG AA or AAA recommendation. WordPress aims to to maintain contrast at the WCAG AA level, which means a ratio of 4.5:1 for normal text and 3:1 for large text. And if you want to see what that would hypothetically look like, you can toggle to test it by clicking on the square icon to the right of the hex values.

Keep in mind that this also applies to a change of state (:focus or :hover) is there is no additional indicator like a text decoration change. Ideally, you’ll have worked out these things in the design phase but sometimes buttons or other smaller elements might fall under the radar. If you want to play with different shades, there are several contract checkers online (for example, here’s one by WebAIM).

ARIA Role and Attribute Validation

ARIA roles and attributes help screen readers understand the purpose of various sections of a web page by assigning certain regions. Certain landmarks should only be applied once per page.

Similar to what we see with styling properties, if it is invalid somehow or being overwritten, it will be struck out when inspected. This is useful to narrow down whether it’s a browser bug, a screenreader bug, or if the markup is just plain ol’ incorrect (as seen in the instance below for the aria-describedby attribute).

Screenshot of Chrome DevTools with an invalid ARIA property value listed

In my journey of learning more about accessibility, debugging has helped solidify how different components interact with attributes, which allows me to read up more and then use them more effectively in the future.

If you weren’t already familiar with these accessibility add-ons in Chrome, welcome to a whole new world! And if you were, is there anything I missed that is a total gem?

The post Accessibility in Chrome DevTools appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/03/06/accessibility-chrome-devtools/feed/ 1 13850
Level Up With jQuery Dimensions https://webdevstudios.com/2016/09/28/level-up-jquery-dimensions/ https://webdevstudios.com/2016/09/28/level-up-jquery-dimensions/#comments Wed, 28 Sep 2016 15:30:29 +0000 https://webdevstudios.com/?p=12873 It’s hard to believe that I’m well into my second year of being a front-end dev here at WDS. It has been an awesome experience and I’m truly blessed to work with such a great group of people. Halfway through 2015, I officially caught the bug known as Javascript and I started really trying to learn Read More Level Up With jQuery Dimensions

The post Level Up With jQuery Dimensions appeared first on WebDevStudios.

]]>
It’s hard to believe that I’m well into my second year of being a front-end dev here at WDS. It has been an awesome experience and I’m truly blessed to work with such a great group of people. Halfway through 2015, I officially caught the bug known as Javascript and I started really trying to learn the language. This inevitably also meant expanding my knowledge of jQuery.

As a quick aside, you might be asking, “jQuery in 2016? Really?” My answer to this is HECK yes. According to BuiltWith, 80% of the top 1 million websites use jQuery.

Learning Javascript is more of a marathon than a sprint.

It’s becoming more and more clear along the way there are concepts and techniques that will really go far in leveling my skill-set as a front-end developer. Two of these concepts are dimensions and offsets. For me, it’s not so much about implementing the code for these concepts but having an in-depth knowledge of their meaning.

It wasn’t until recently that I started experimenting with the real power of each concept. Use them in conjunction and you can do some pretty crazy DOM manipulation!

For this post, we will focus on dimensions and follow up with another post on offsets.

jQuery provides six functions that we can use to get the height and width of an element. Your first response might be why is there a need for six functions just to get the height and width of an element? The answer…the box model. Height and width can vary depending on if you are including padding, borders, and margins.

Let’s take a brief look at each function jQuery provides along with a quick explanation. Remember: Like other jQuery functions, these are both getters and setters. Passing in a value to the function makes them a setter.

Height

.height() – Will return the height of the content. In the image below, the content is the dark grey area.

.innerHeight() – Returns the height of the content + padding.

.outerHeight() – This will return the value of the content + padding + border.

.outerHeight( true ) – Returns the value of content + padding + border + margin.

height-c

Width

.width() – Returns the width of the content. The dark grey area in the image below.

.innerWidth() – Returns the width of the content + padding.

.outerWidth() – Returns the width of the content + padding + border.

.outerWidth( true ) – Returns the width of the content + padding + border + margin

width-c

How About a Use Case?

There have been many times when I’ve needed to transform a primary desktop menu into both a ‘tablet’ or ‘mobile’ menu depending on the width of the browser. You can make this happen seamlessly with a combination of CSS and jQuery. The approach is simple. Fire an event that will change the CSS appropriately and perform any other DOM manipulations when the browser size is above or below a certain breakpoint.

Here is a nifty little function that will do exactly what we need it to. (Thanks for Aubrey for this nice utility function.)

/**
 * Check if window width is equal or less than breakpoint
 * 
 * @param breakpoint Width to check against
 **/
function screenLessThan ( breakpoint ) {
    
    // Get the width of the current window
    var windowWidth = $( window ).width();

    // Return true/false if window with is equal or smaller than breakpoint
    // parseInt() is being used to ensure we are working with integers
    return ( parseInt( windowWidth ) <= parseInt( breakpoint ) );
}

We can leverage the function above to allow us to make certain changes based on the current size of the browser! In the gif below, we are making both the background color and text change based on breakpoints that the function above is checking against.

mobile tablet desktop

Checkout the CodePen below to view the full code. Also, feel free to let me know of ways this code could be optimized!

The Takeaway

Learning and understanding what each of these dimension functions do will level up your skill-set! I’d recommend taking a bit of time to play around with them by combining them with different events. Having familiarity with them is HUGE in my book.

The post Level Up With jQuery Dimensions appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/09/28/level-up-jquery-dimensions/feed/ 1 12873
The Six Questions Developers Need to Ask Before Turning in Tasks https://webdevstudios.com/2016/09/01/six-questions-developers-need-to-ask/ https://webdevstudios.com/2016/09/01/six-questions-developers-need-to-ask/#respond Thu, 01 Sep 2016 17:05:30 +0000 https://webdevstudios.com/?p=13578 Everyday I spend time working on products for our great clients, I specifically spend a great deal of it writing code and building features. But I’m not just creating new features, I’m also creating new opportunities…opportunities to break that product. Here are the questions developers need to ask before turning in their tasks, and how they’re going to help Read More The Six Questions Developers Need to Ask Before Turning in Tasks

The post The Six Questions Developers Need to Ask Before Turning in Tasks appeared first on WebDevStudios.

]]>
Everyday I spend time working on products for our great clients, I specifically spend a great deal of it writing code and building features. But I’m not just creating new features, I’m also creating new opportunities…opportunities to break that product. Here are the questions developers need to ask before turning in their tasks, and how they’re going to help you code smarter.

  1. How can I break this?
  2. Where’s Murphy hiding?
  3. Who do I trust?
  4. What’s dangerous?
  5. What are the real limits?
  6. Who is this for?

For example, what could go wrong with this example?

<?php _e( 'What could go wrong here?' ); ?>

Well, it turns out, a lot.

Developers, ask yourself these six questions before turning in any task

Have you ever tried breaking this by adding malicious scripts in language file? Turns out an innocent function, like this, opens a huge opportunity for people to break things. This was my own revelation a few weeks ago, and it dawned on me that I do not spend enough time trying to break things and learning the skills I need to detect these hidden opportunities in my code. The first step was simply realizing that with every new feature, comes new opportunities, but the following are a few steps I’ve been taking before I complete and turn in any new feature.

How can I break this? (Go break it)

A man hackingDuring the drudge of daily tasks and code commits, we often can overlook the need to go in and actually break things we build. The definition of hacking isn’t necessarily malicious; it’s simply taking something and re-purposing it for a different reward. MacGyver was famous for this kind of hacking! That said, hacking is commonly used to break things, and that’s what we’re looking to fix, which is why we should try to break our own stuff.

It takes more than just trusting functions and methods to get the job done. You have to actually get in there and try and break what it is you just made. I feel we aren’t encouraged enough to go in there (and especially spend the time) and be a hacker. But I call all developers out! Become a hacker daily! Break your stuff! In doing so, you are going to build better products, serve your clients better, increase the reliability of your company, and, ultimately, become a better developer.

I also encourage CEOs, business owners, leads, and project managers to change the rhetoric behind security to go beyond just coding, but making the actual act of hacking your own solutions a part of the development process. Tell your developers to ask themselves, before turning in a task or pull request, “How can I break this?” And give developers permission to take the time to become a hacker.

Where’s Murphy hiding?

Anything that can go wrong, will go wrong. – Murphy’s Law

So we’re trying to hack our new feature, and we find a way that a user can pass a combination of query arguments, and somehow, logged in as a subscriber, could possibly run a server-intensive script we just built over and over. I feel (admittedly, through my own experience) we tell ourselves too much that they would never figure out how to do that, and we move on. But someone will!

I’ve just created a problem that will happen in the future. Thinking of these findings as problems that will undoubtedly happen, no matter how unlikely we think it is, will help us keep the internet and clients safe. It allows us to strategize.

Who do I trust?

Developers can be too trusting, and we shouldn’t be. Never trust anyone.

<?php _e( 'What could go wrong here?' ); ?>

In our example here, we might admit that the only one who could really cause a problem are the people who translate. Maybe they’re our own people, maybe they’re strangers, or maybe they’re future translators that a client hired six months down the road that know nothing about WordPress. Whoever it is, I say, they automatically get the “I don’t trust you” stamp of non-approval. It’s strange, but developers have to live in a very untrustworthy world, and we’re better developers for it! Having an skeptical approach will lead you to creating more secure code and features. Take your paranoia and make something rock solid.

What’s dangerous?

Skull and bones poison

In the spirit of Murphy’s Law and trusting no one, you have to see information itself as a potential transmitters for viruses, illnesses, and things that cause bad things to happen and blow up the Internet. Data and information are dangerous! By shifting your view of information to something dangerous, and hiding some disease inside, we can be better devs.

An example.

$image = get_the_post_thumbnail();
echo $image;

In this example, we might view $image as completely innocent and trustworthy.

But it’s not.

Did you know that get_the_post_thumbnail() has a filter? Yeah, it’s post_thumbnail_html and anyone can filter the output and push out a harmful script! $image is dangerous; variables are dangerous! How do you know someone with server access didn’t inject a Must-Use plugin that filters that output?

If we put on our Hat Of Mistrust, we’ll be aware that leaving that variable alone is risky, and take action:

$image = get_the_post_thumbnail();
echo wp_kses_post( $image );

This should allow img tags that are allowed in the WordPress post editor, and if anyone tries to inject a harmful script, it won’t let them. We need to start seeing information as potentially dangerous, and ask ourselves if it is, because we don’t know all the filters or ways people can turn information against us. Using critical thinking and strategy in the ways we work helps us stay one step ahead of people who either don’t know or possess malintent.

If we were really paranoid, we might write something like:

$image = get_the_post_thumbnail();
echo ( is_string( $image ) && stristr( $image, '<img' ) ) ? wp_kses_post( $image ) : '';

What are the real limits?

Another question I think developers rarely ask themselves are, “What are the real limits?”

Really thinking about this question can produce interesting answers.

For instance, what is the limit of get_posts? At first, you might think, well -1 (I did). Set that posts_per_page to -1 and we’ll get all the things, yeah baby! But, a smarter developer might find that…

  • The server’s execution time is a limit
  • The server’s memory is a limit
  • 15, the limit is 15; there will always be 15

We should be thinking about real limits, not just limits in code, and what happens when these limits are reached. Like the server’s execution time or memory limits resulting in a 503. Or, getting fifteen posts–no harm there, right? Have you ever asked yourself how many posts_per_page actually result in a timeout or a 503 on your server? It’s a good question.

Our job as developers is to eliminate the harmful effects of reaching real limits and we need to be aware of what these limits are and make sure we’re not breaking them.

Who is this for?

Zoolander, what is this a center for ants?The last question I pose developers to ask is,

“Who is this for?”

I think every feature should have a name associated with it. Is it all administrators, or all authors? Is it just Jane or Joe? Is it the United States? Are they English speakers or Spanish speakers? Who are these people!?

Knowing (or even guessing at) who will be using our features, by giving our features ownership, helps make sure we’re prepared to create features with privilege in mind.

Even if your answer is “everyone,” we probably should be looking hard at the detailed, real time answers. For instance, “everyone” includes many languages; how many Spanish speakers need to use your product? Do you have a plan to have your content translated? What about A11y? That includes everyone too! Thinking of your features as privileged and belonging to someone helps us take more responsibility with our features, who has access, and who shouldn’t. This also allows you expand your reach and make sure that people who might otherwise be excluded in a generic “everyone” can access what you made.

What about you?

Do you have any tactics that help you build more secure features? What are some ways you work secure features into your build?

The post The Six Questions Developers Need to Ask Before Turning in Tasks appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/09/01/six-questions-developers-need-to-ask/feed/ 0 13578
Winning With Code Reviews https://webdevstudios.com/2016/08/25/winning-code-reviews/ https://webdevstudios.com/2016/08/25/winning-code-reviews/#respond Thu, 25 Aug 2016 17:36:34 +0000 https://webdevstudios.com/?p=13339 Here at WebDevStudios we put a lot of emphasis on code quality. After handing off a product to a client, we never know who may be looking at and/or maintaining our code. We want to be proud and confident that the next person will not have an OMGWTFBBQ-head-smashing-into-keyboard moment, but one of delightful surprise. How Read More Winning With Code Reviews

The post Winning With Code Reviews appeared first on WebDevStudios.

]]>
Here at WebDevStudios we put a lot of emphasis on code quality. After handing off a product to a client, we never know who may be looking at and/or maintaining our code. We want to be proud and confident that the next person will not have an OMGWTFBBQ-head-smashing-into-keyboard moment, but one of delightful surprise.

How do we consistently create and maintain a high level of quality code? Through peer code reviews.

All developers at WebDevStudios are encouraged to request code reviews and to provide their own feedback to others on their code review requests.

Peer code reviews have enhanced the code quality at WebDevStudios by leaps and bounds. Now instead of coding in a hole, all the developers are actively striving to write good, clean code that will pass a code review the first time. Instead of feedback coming in the form of correction from a (busy) lead it has become a game amongst the developers to see who can write the most elegant and bug free code the first time out the gate. As a result, the coding standards and practices at WebDevStudios have grown and enhanced.

This all sounds good, but how does it work in practice?

When we receive a new project, it goes through an architecting phase that identifies all the key elements that will be required. These elements are then further broken down into their respective features. We utilize the Git code versioning system and its branching model to create a unique branch per feature, which we have detailed in a previous post titled An Alternative Git Flow for Client Work.

After a developer has finished a feature and before merging it back into the main branch, a code review is requested. Doing the code review at this step allows the reviewer to see all of the changes made on the feature branch compared to the main branch quite easily. The reviewer can then switch between branches to verify the feature code works and, if so desired, merge the feature into other branches to review against.

Reviews may be done by more than one other developer and have sometimes spurred incredible conversation and debate on the merits of performing an operation this way versus that way.

Code reviews promote healthy culture

As developers we are very proud of our code. Code is our form of art–where we express our inner Rembrandt. As such, critique of our artistry can be a stinging blow to our egos. I have seen instances where developers have nearly come to (virtual) blows when one suggests a change to the other’s code. Creating a healthy culture for code reviews counters any negative feelings that may arise.

We are all on the same team and we all have the same goal: To deliver the highest quality product to the client. When I was young my mother used to tell me, “If you do not have anything nice to say do not say anything at all.” We have applied the same motto to our code reviews. Feedback is never negative, but always constructive. By using positive language and helpfully showing each other new tricks and techniques, the skills of WDS devs have increased across the board and we have grown closer as a team.

Code reviews enhance security

Let’s admit it: All of us have written some code with a vulnerability issue. The most common of which is SQL injection points through unsanitized input. While coding, it is easy to become wrapped up in getting the feature done and lose sight of all the security implications of what you are writing. Having another set of eyes review the code can help to identify weaknesses.

This is further backed up by looking at a few of the major exploits that have been found in the WordPress ecosystem this year alone. Many of them were not found by probing the application, but by looking at the released source code and finding some place allowing unsecured input.

Code reviews increase social recognition and a feeling of self-worth

This may sound strange but there is powerful psychology behind code reviews. Providing code reviews causes us to feel good about helping out another, and receiving a code review that does not indicate anything needs to be updated in your code becomes almost a drug unto itself. Developers tend to amp up their game to “beat” the reviewers. Even us lead developers have our code reviewed, and I can tell you that nothing excites the team more than poking holes in code of the “best” developers on the team. (…Yeah, I had a code review only critiquing my use of white space…).

aziz ansari gif, code reviews, the importance of code reviews, why do code reviews, what is a code review, should lead developers do code reviews, how to do a code review, what's the point of a code review

Is it really worth the extra time?

When working on client projects time is of the essence, so we had to ask ourselves, “Is this worth the extra time it will take to develop a feature?”

The resounding answer is YES!

The increase in code quality and skills of the developers alone makes code reviews worth it, and the added benefit is finding bugs to be squashed well before being introduced in production.

According to a 2002 report by the National Institute of Standards and Technology a bug found post-production takes 18.7 hours to find and fix while a bug found during a code review takes just 3.2 hours to fix! That is 15.5 hours saved! What “extra time” are you worried about!?

Go forth and review thine code

As you can see, the idea behind code reviews is a simple one but it has BIG benefits. I want to encourage you to begin integrating code reviews into your workflow.

You may not have a team like we do here at WebDevStudios, but if you are reading this, you are part of the team of the community. WebDevStudios is just one fish in this pond that we call WordPress. Together, we are all striving to enhance this product that we use and love. Now get out there and start doing those code reviews!

I would love to hear about your experiences with code reviews in the comments and how your company or organization has implemented them.

The post Winning With Code Reviews appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/08/25/winning-code-reviews/feed/ 0 13339
A Beginner’s Guide to Writing Bash & Shell Scripts https://webdevstudios.com/2016/07/07/beginners-guide-writing-bash-and-shell-scripts/ https://webdevstudios.com/2016/07/07/beginners-guide-writing-bash-and-shell-scripts/#comments Thu, 07 Jul 2016 12:00:15 +0000 https://webdevstudios.com/?p=13281 Optimizing your development workflow is one of the most important things a developer can do. Being able to leverage your tools quickly and efficiently lets you spend your time working on actual development–instead of fighting your tools or doing boring, repetitive things. A few months ago, I wrote a blog post about getting set up Read More A Beginner’s Guide to Writing Bash & Shell Scripts

The post A Beginner’s Guide to Writing Bash & Shell Scripts appeared first on WebDevStudios.

]]>
Optimizing your development workflow is one of the most important things a developer can do. Being able to leverage your tools quickly and efficiently lets you spend your time working on actual development–instead of fighting your tools or doing boring, repetitive things.

A few months ago, I wrote a blog post about getting set up with the command line and starting to use some of the tools that are available. If you have not read that post yet, I’d recommend doing so, or at least glancing through it before getting into this post.

The main reason I built vv was because I was tired of manually setting up sites on VVV for every new project. Most features inside of vv were built to automate something that I or someone else did manually with every new project. This mindset is important to get into when developing; it’s why we learn keyboard shortcuts, why we use things like theme frameworks, and even why we use WordPress. Doing things over and over again is boring.


writing bash scripts, writing shell scripts, writing bash and shell scripts, brad parbs, WebDevStudios, web development tutorials, web development, development tips, programmer tips, programming tips, programming, programming tutorials, speed up your development, speed up my development, learn to develop faster

Getting Started

To get started writing our first Bash script, we simply need to make a file in a position where our shell can locate it. We can easily do this by checking which locations are in the $PATH environmental variable, as that’s where our shell looks for executable files. To view this, simply open up a terminal and do echo $PATH. This should give you an output that looks something like: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/go/bin

This is a list of folders, separated by ‘:‘s. All of these folders are locations where your shell looks for executable scripts when you run them by name. So placing a ‘hello-world’ script in any of these locations would let you run hello-world in your terminal.

When writing scripts that you want to use in more than one place on your computer, you’ll want to either save the script into one of those folders or you’ll want to add a new folder to your $PATH.

Bash Basics

Writing our first Bash script

To begin writing our first Bash script, we need to make a new file and add a special line to it. The ‘shebang’ is always the first line in a Bash script, and it defines what shell should run this script. This is usually always going to be Bash, but in some cases in might be something else.

#! /bin/bash is usually what is used here, but I recommend using #! /usr/bin/env bash because it is better for portability. /bin/Bash is the exact location of the Bash executable, whereas /usr/bin/env bash is grabbing the environmental variable that contains Bash. This means Bash can be located in a different location.

Now that we’ve added this this first line, you’ll want to save your file with a name. You can either have no extension, or a .sh extension. If you save it, and go into the directory where it is saved, you can run ‘./your-file-name’ and it should execute the script. If you get a permission denied error, you’ll need to run ‘chmod +x your-file-name‘ to allow it to be executable.

Earlier, we talked about the $PATH. You can store Bash scripts in any of those locations, or add a new location, and then you’ll be able to run your script anywhere on your system by just running ‘your-file-name‘. I recommend this for any scripts that aren’t project-specific.

Basic Bash

The way Bash works is pretty simple. A Bash script is set of commands. Anything you run on the command line, you’ll be able to run in a Bash script. Most Bash scripts are structured as a list of commands, usually with some helper functions, and some checks on whether or not to run different things.

Let’s start writing a very basic ‘Hello, World,’ script, as is the norm for learning a new language. We’ll start off with a shebang, and then it’s simply echo "Hello, World". So your script would look like this:

   #!/usr/bin/env bash
   
   echo "Hello, World"

Now that we’ve written our required ‘Hello, World,’ program, let’s get into something that can be a but more useful. First, we want to understand some of the flow and constructs in Bash programming.

Functions

Like most languages, bash programs do have functions. You can define these one of two ways. You can use the ‘function’ keyword, or you can leave it off. A function looks like this:

    function my_cool_function() {
        # Some code here
        echo "Hello!"
    }
    
    #calling our function:
    my_cool_function

One thing you’ll notice is that I left off the () and the semicolon when calling my function. In Bash, semicolons at the end of lines are optional. I tend to not use them, but others prefer having them in there. The same with the parentheses–I choose to leave them off if there are no arguments, for ease of readability.

One important note about functions: In Bash, you must define your function before calling it. Bash scripts are executed in the order of the lines in the file, so calling a function before you define it will cause an error.

In a bit, we’ll talk about passing arguments to functions, as well as returning values from your functions.

Control flow

One of the things that really tripped me up when I started learning Bash was if/else statements. These are treated a bit oddly in Bash.

Your basic if / else looks like this:

    if [[ "$value" == "check" ]]; then
        # do something
    else
        # do something else
    fi

Seems pretty straightforward, but the two things you’ll want to note are the fi at the end, signifying the end of the if statement, as well as the double [[ inside the check. The double brackets is a bit confusing, so for simplicity sake, just remember that using two brackets instead of one is safer and has a few nice features.

Variables

Now that we’ve talked about if / else statements, let’s chat about variables for a minute. Variables in Bash need some care when you work with them.

First, assigning a basic variable, and echoing it out:

    my_var="my text"
    
    echo "$my_var"

You’ll notice when we echoed it (and anytime we’d use it for anything) that there is a dollar sign in front of it. You don’t need that when you’re assigning the variable though. The next important thing is that we put quotes around it when we used it.

This is something that most people don’t do, but it is very important when you start accepting user input or deal with filenames/file paths. The quoting prevents what’s called “word splitting.” If you were to set the variable to be a filename, and that file name happened to have a space in it, Bash would assume that space meant you were passing in two arguments, rather than one. Most of the time you want to treat your variable as exactly what it is, so its a good rule of thumb to always put your variables in quotes when using them.

Passing in values

When calling your script from the command line, you can easily pass in values.

    $./myscript.sh val1 val2

These arguments are quite easy to read in Bash. They automatically get assigned to the variables $1, $2, $3 for each passed in argument. You can also use the handy $@ variable to access everything.

Running this:

   #!/usr/bin/env bash
    echo "$1"
    echo "$2"
    echo "$@"

…as this:

    $./myscript.sh val1 val2

…would output this:

val1
val2
val1 val2

You can also access arguments passed into functions inside of your script the same way, as well as passing in values inside your script the same way.

Reading variables from a prompt

In your scripts, you most likely will at some point want to prompt for some information. Be it a file name, path, times to run, etc. This is quite simple.

    read -r variable_name

This will put the results of the prompt into the variable.

Generally, you’ll want to echo out your question before it, like so:

    echo "What is your favorite color?"
    read -r color
    echo "Your favorite color is $color."

Subshells

Inside of your Bash script, you’ll probably want to return values in your functions. In most programming languages, this is as simple as doing ‘return $x.’ For a lot of built-in shell commands, we probably want to get what they normally output. Saving the current directory we are in, for example. The way we do it is by echoing our return value inside of our function, and then calling that function inside of what is called a subshell, and capturing the output.

This is handy, as it lets us use any available bash function to return a value. For example, we can caputure the output of lsby calling it in a subshell.

    directories="$(ls)"

This would set the variable $directories to contain a listing of files in the current directory. Behind the scenes, a subshell executes the code in a different processing thread, so all output is captured, and not printed to the screen.

Helpful tools for writing scripts

Shellcheck

My favorite tool for Bash scripting is shellcheck. Available at http://shellcheck.net, as well as a downloadable command for every platform from Github. Shellcheck is basically a linter for scripts. Running your script through it will surface everything from parse errors, syntax mistakes, and a whole lot more.

The best part of Shellcheck is that not only does it tell you what is wrong, but it will also clue you in on why it is wrong and what that means. For example, if we had this code, which accepts one argument, switches to that directory, and then echoes out what directory we are in.

   #! /usr/bin/env bash
   
    cd $1
    $path = $( pwd )
    echo $path

Running this through Shellcheck gives us these errors:

$ shellcheck myscript
 
Line 3:
        cd $1
        ^-- SC2164: Use cd ... || exit in case cd fails.
           ^-- SC2086: Double quote to prevent globbing and word splitting.
 
Line 4:
        $path = $( pwd )
         ^-- SC1066: Don't use $ on the left side of assignments.
              ^-- SC1068: Don't put spaces around the = in assignments.
 
Line 5:
        echo $path
             ^-- SC2086: Double quote to prevent globbing and word splitting.

As you can see, there are a lot of mistakes here, but they all are fixable in a few seconds. Following those directions, we end up with this block of code, which throws no Shellcheck errors.

    #! /usr/bin/env bash
   
    cd "$1" || exit
    path=$( pwd )
    echo "$path"    

As you noticed in the above error example, the errors started with “SC####”. All errors that Shellcheck shows have relevant pages with information on Github. For example, SC2086 will explain the rationale behind why you should do it the way they suggest.

Explain Shell

ExplainShell.com is another great resource. By pasting in a full Shell command with flags and options, it will parse out what everything means and explain it. For example, this command will list all files in the directory:

    find . -type f -print0

Running this through ExplainShell will out what each of those options / arguments do.

explainshell

Writing your first script

Although not everything in Bash was covered in this post, you should have enough knowledge now to start making a basic script. Once you start writing scripts, you’ll learn more and more about the language, as you try to automate more and more tasks.

Let’s write a script together!

One thing I have to do sometimes when getting spun up on a new project is running a few dependency installation scripts. Most of the time it is npm install, bower install, and maybe composer install. Let’s write a script to do that for us:

    #! /usr/bin/env bash
    
    echo "Installing all the things..."
        
    echo "Installing npm requirements..."
    npm install

    echo "Installing bower packages..."
    bower install
    
    echo "Installing composer packages..."
    composer install
    
    echo "Finished installing."

This script above will run all the commands we want. However, maybe there are some projects where you might not use composer, so rather than just attempting to run the install commands, let’s first check to see if the relevant .json files exist first.

    #! /usr/bin/env bash
    
    echo "Installing all the things..."
    
    if [ -f "package.json" ]; then
        echo "Installing npm requirements..."
        npm install
    fi
    
    if [ -f ".bowerrc" ]; then
        echo "Installing bower packages..."
        bower install
    fi
    
    if [ -f "composer.json" ]; then
        echo "Installing composer packages..."
        composer install
    fi
    
    echo "Finished installing."

That’s much better. Now, if there isn’t anything to install, we won’t even try to. The last step is saving this somewhere into our $PATH folder listing and then we can run it in a project directory.

That was a pretty simple script to write, and now we can easily install all our project dependencies very easily. Another good change might be to also allow for passing in arguments that will toggle between an install and an update. I’ll leave that as an exercise for you.

There are a ton of things you can do to automate your workflow. Hopefully with this very basic knowledge of Bash, you’ll be able to start making your life a bit easier.

The post A Beginner’s Guide to Writing Bash & Shell Scripts appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/07/07/beginners-guide-writing-bash-and-shell-scripts/feed/ 2 13281
Helpful Books for Front-End Developers https://webdevstudios.com/2016/07/05/books-for-front-end-developers/ https://webdevstudios.com/2016/07/05/books-for-front-end-developers/#respond Tue, 05 Jul 2016 16:49:46 +0000 https://webdevstudios.com/?p=13271 “Please, no matter how we advance technologically, please don’t abandon the book. There is nothing in our material world more beautiful than the book.” –Patti Smith There are many great pathways to glean new information out there, whether it be on the web or in a class. Your mileage may vary depending on your learning Read More Helpful Books for Front-End Developers

The post Helpful Books for Front-End Developers appeared first on WebDevStudios.

]]>

“Please, no matter how we advance technologically, please don’t abandon the book. There is nothing in our material world more beautiful than the book.” –Patti Smith

There are many great pathways to glean new information out there, whether it be on the web or in a class. Your mileage may vary depending on your learning style or the topic at hand. With the tech industry, evolution often occurs at a faster rate than print media can keep up.

Still, sometimes a good ol’ print version of what you need comes along that earns its place on your bookshelf. Maybe it got there after you heard it mentioned for the tenth time. Maybe it is the book you always find yourself lending out to someone when they want to dip their feet in to a new niche (regardless of the evolution of name-your-favourite-framework-here.js). Maybe it is the book that someone leant to you at a crucial step of your learning. There are brilliant books for front-end developers out there–and they are definitely worth looking over.

A single book won’t be able to provide you with the breadth of information necessary, especially with today’s multi-dimensional coding ecosystems. Often, books cite wonderfully curated online resources so you are able to use their foundation as a jumping off point for knowledge expansion.

The WordPress-specific

WebDevStudios is abundant with people who know more than a few things about WordPress–with a stack of books to their credit, no less! One book from this list is Professional WordPress: Design and Development, which starts from a top-level view on WordPress then digs down into all the nitty-gritty. Sure, I’m biased, but this is a wonderful additional to any WordPress developer’s bookshelf.

The Process

For those who want to know more about the principles of intuitive navigation and information design, Don’t Make Me Think: A Common Sense Approach to Web Usability, by Steve Krug, is an excellent straight-forward resource for both beginners and the more-seasoned on how people connect with interfaces. This is a good resource for management, designers, and developers alike.Print book covers displayed in line

The Visual

Are you more visually inclined? Jon Duckett’s books on HTML/CSS and JavaScript/jQuery may be a good fit. They each include code examples and there is a general assumption of little-to-no previous programming experience that make these a good beginner’s starting point and reference.

The Varied

Smashing Magazine offers many great resources and one compilation is Smashing Book 5: Real-Life Responsive Web Design. While responsive design is a default these days, this gathers techniques and strategies on everything from workflow to SVGs to debugging. (There is a level of assumed knowledge and experience in many chapters.)

The Non-Code Code Books
  • Code: The Hidden Language of Computer Hardware and Software: Starting with Morse Code and working its way linearly through telegraphs, barcodes and I/O devices, this isn’t going to teach you how to better implement code but you will likely have a new respect for the history behind the work you’re doing (Published in 2000, so don’t expect discussion of technologies beyond)
  • Quiet: The Power of Introverts in a World That Can’t Stop Talking: Okay, this one has truly nothing to do specifically with code. This book explores the dominant values of business culture and how the leadership potential of introverts is often overlooked.

What are some other must-reads that you have on your bookshelf?

The post Helpful Books for Front-End Developers appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/07/05/books-for-front-end-developers/feed/ 0 13271