programming Articles / Blogs / Perficient https://blogs.perficient.com/tag/programming/ Expert Digital Insights Tue, 12 Nov 2024 16:28:18 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png programming Articles / Blogs / Perficient https://blogs.perficient.com/tag/programming/ 32 32 30508587 Understanding Debouncing and Throttling in JavaScript – A Comprehensive Guide https://blogs.perficient.com/2024/11/12/understanding-debouncing-and-throttling-in-javascript-a-comprehensive-guide/ https://blogs.perficient.com/2024/11/12/understanding-debouncing-and-throttling-in-javascript-a-comprehensive-guide/#respond Tue, 12 Nov 2024 10:56:02 +0000 https://blogs.perficient.com/?p=371786

Throttling and debouncing are two essential optimization strategies. In this comprehensive guide, we will delve into the concepts of debouncing and throttling, explore their use cases, and understand how to implement them in JavaScript.

Debouncing Explained

What is Debouncing?

Debouncing is a programming technique used to prevent time-consuming operations from running too frequently, which might cause a web application’s performance to lag. It forces a function to wait a certain amount after the last invocation before executing.

When to Use Debouncing?

  1. Input Fields: Debouncing is often applied to input fields to delay the execution of a function until the user has stopped typing. This prevents unnecessary API calls or other resource-intensive operations on every keystroke.
  2. Resize and Scroll Events: When handling events like window resizing or scrolling, debouncing helps avoid performance issues by limiting the frequency of function calls.

Debouncing Implementation

Let’s look at a basic implementation of a debounce function in JavaScript:

const debounce = (func, delay) => {
    let timeoutId;
    return (...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
};

Example usage:

const debouncedFunction = debounce(() => {
console.log("Debounced function called");
}, 300);
// Attach debounced function to an event, e.g., button click
document.getElementById("myButton").addEventListener("click", debouncedFunction);

 

Scenario: Search Input in an E-commerce Site

When a user types in a search input box, you want to wait until they stop typing before sending the search query to the server. This prevents sending a request for every keystroke.

Scenario: Autosaving

When a user writes a document or fills out a form, you might want to autosave their input only after they’ve stopped typing for a certain period.

Throttling Explained

What is Throttling?

Throttling is a technique that ensures a function is only executed at a certain rate, limiting the number of times it can be called over time. Unlike debouncing, throttling guarantees the execution of a function at regular intervals.

When to Use Throttling?

  1. Scrolling: Throttling is beneficial when handling scroll events to control the rate at which a function is executed. This prevents overwhelming the browser with continuous function calls during rapid scrolling.
  2. Mousemove Events: Throttling is useful for mousemove events to prevent excessive calculations when tracking the movement of the mouse.

Throttling Implementation

Here’s a basic implementation of a throttle function in JavaScript:

const throttle = (func, limit) => {
    let throttled = false;
    return (...args) => {
        if (!throttled) {
            func.apply(this, args);
            throttled = true;
            setTimeout(() => {
                throttled = false;
            }, limit);
        }
    };
};

Example usage:

const throttledFunction = throttle(() => {
console.log("Throttled function called");
}, 300);
// Attach throttled function to an event, e.g., window scroll
window.addEventListener("scroll", throttledFunction);

 

Scenario: Window Resize Event

When a user resizes the browser window, the resize event can fire many times per second. Throttling can ensure the event handler executes at most once every 100 milliseconds, reducing the number of times the layout or other elements need to be recalculated.

Scenario: Scrolling Event

When a user scrolls a webpage, the scroll event can fire many times. Throttling can ensure the event handler executes at most once every 200 milliseconds, which is useful for tasks like lazy loading images or infinite scrolling.

 

Debouncing vs. Throttling

Debouncing and Throttling Differences

Execution Guarantee:

  • Debouncing: Ensures that a function won’t be run until a predetermined amount of time has elapsed since its last call.
  • Throttling: Guarantees a maximum number of executions in a given time frame.

Frequency of Execution:

  • Debouncing: Delays a function’s execution until a predetermined amount of time has passed since the last call.
  • Throttling: Ensures a function is not executed more often than once in a specified amount of time.

Use Cases:

  • Debouncing: Ideal for scenarios where you want to wait for a pause in user input, such as typing or resizing.
  • Throttling: Suitable for scenarios where you want to limit the frequency of function calls, such as scroll events.

Choosing Between Debouncing and Throttling

    • Debouncing is suitable when:
      • You want to wait for a pause in user input before taking an action.
      • You want to delay the execution of a function until after a certain time has passed since the last invocation.
    • Throttling is suitable when:
      • You want to ensure a function is not called more frequently than a specified rate.
      • You want to limit the number of times a function can be executed within a given time frame.

Conclusion

Debouncing and throttling in JavaScript are essential tools in a web developer’s kit for optimizing the performance of functions. By understanding these concepts and knowing when to apply them, you can significantly improve the user experience of your web applications. Whether you need to delay API calls during user input or control the rate of function execution during scroll events, debouncing and throttling provide elegant solutions to common challenges in web development.

]]>
https://blogs.perficient.com/2024/11/12/understanding-debouncing-and-throttling-in-javascript-a-comprehensive-guide/feed/ 0 371786
Understanding the Shadow DOM in Web Components https://blogs.perficient.com/2024/02/15/understanding-the-shadow-dom-in-web-components/ https://blogs.perficient.com/2024/02/15/understanding-the-shadow-dom-in-web-components/#respond Thu, 15 Feb 2024 09:45:27 +0000 https://blogs.perficient.com/?p=356540

Managing the structure and styling of components in web development may frequently become complex, particularly when working on large-scale projects with several developers or integrating third-party components. Because CSS is global, there is a chance for CSS conflicts and accidental styling changes, a common issue for developers.

Here’s where the Shadow DOM comes in as a problem-solving tool:

What is Shadow DOM?

Shadow DOM serves as an effective safeguard for web components. It encapsulates their styles and structure, preventing them from messing with the rest of the webpage. It’s a way to create independent components that don’t conflict with global styles, making your code more modular and reusable. Consider it granting each component its own personal space to perform its tasks.

Creating Shadow DOM: A Step-by-Step Guide

Let’s see a simple code example and learn how to use shadow DOM to create custom elements by creating a simple Login Form.

So, to create a custom element, first, we must create a class that should extend from the HTML element class.

We will add a constructor and call the super function. If we don’t call the super function, then this class’s ‘this’ keyword will not be initialized.

Picture1

Now, let’s create a shadow element by using the attachShadow method. In this method, we need to provide an object with the mode value; it can be either open or closed.

shadow element

Create a root element ‘form‘ by calling document.createElement, and the reference will be stored in the form variable.

root element

Now, let’s create the labels and inputs for the Username and Password, as well as the button for the Submit form.

Picture4

Next, we’ll add text to the labels and button using the ‘textContent‘ property and set the ‘types‘ and ‘placeholder‘ attributes for the form and its inputs using the ‘setAttribute‘ method.

Picture5

Applying styles to the Shadow DOM.

Picture6

Let’s start to append form and its elements to the Shadow DOM

These two lines will append the ‘<style>’ element containing the styles specific to the login form, and the form element, which serves as the container for the login form components, is appended to the Shadow DOM.

Picture7

The elements usernameLabel, usernameInput, passwordLabel, passwordInput, and submitButton are appended to the form element within the Shadow DOM, composing the login form.

Picture8

Here, we’re registering the ‘LoginForm‘ class as a custom element named ‘login-form.’ This enables us to utilize the ‘<login-form></login-form>‘ tag within our HTML document to instantiate instances of the login form component.

Picture9

This is the outcome of our customized login form, which shows the UI of the login form on the left and its code structure on the right.

shadow dom result

Understanding the Shadow DOM elements

  • <login-form> is the custom HTML element defined in the code using customElements.define().
  • #shadow-root (open) indicates the presence of a Shadow DOM for the <login-form> element, which encapsulates its internal structure and styling.
  • Inside Shadow Element, there’s <style> element, which contains CSS style specific to the login form.
  • The < form> element contains input fields for username and password and a submit button. This is also part of the Shadow DOM.

Shadow DOM Components

Shadow DOM components maintain their own styles and structures, like segmented bubbles within a webpage. They encourage modularity, which keeps global styles from influencing one another. Consider them as independent components that follow their own set of guidelines, improving the maintainability and reusability of the code.

How Does Styling Work Within the Shadow DOM?

Styles defined within the Shadow DOM remain contained within the scope of the component, thus ensuring encapsulation. They don’t affect other sections of the page.

Styles are basically individual instructions for every element. In the above example, the Login form component’s styles are unique to that form alone. It ensures a personalized look without interfering with the rest of the website, much like providing each piece its own set of guidelines.

Benefits of Encapsulation and Isolation

The ability to provide encapsulation and isolation has several significant benefits for building modular and maintainable code:

  • Modularity and Reusability

The Shadow DOM-encapsulated components function as modular construction blocks. Their reuse in different areas of a project or across multiple projects can contribute to the optimization and grading of the code base and its scalability.

  • Prevent Style Clashes

Encapsulation ensures that styles defined in a component remain limited to that specific component. This prevents unwanted conflicts with the overall styles of the web page and maintains a clean and predictable visual presentation.

  • Reduced Global Impact

Isolation prevents external scripts or styles from affecting the internal behavior of the component. This minimizes the possibility of unwanted consequences, which simplifies the justification and long-term maintenance of code.

  • Improved Debugging

Encapsulation facilitates easier debugging, allowing debugging processes to target issues within a component more quickly and precisely without worrying about how modifications might affect other application areas.

Conclusion

To put it simply, knowing how to use and comprehend the Shadow DOM allows us to create web elements that are not only visually appealing but also simple to reuse and manage. It streamlines the entire web-building process by giving every section of our website its own mini fortress. Cheers to your next coding adventure!

]]>
https://blogs.perficient.com/2024/02/15/understanding-the-shadow-dom-in-web-components/feed/ 0 356540
Leveraging ChatGPT For Professionals: Part 2 https://blogs.perficient.com/2024/02/07/leveraging-chatgpt-for-professionals-part-2/ https://blogs.perficient.com/2024/02/07/leveraging-chatgpt-for-professionals-part-2/#respond Wed, 07 Feb 2024 17:09:10 +0000 https://blogs.perficient.com/?p=353216

In part 2 of this series, we break down how professionals can leverage ChatGPT to code. This blog breaks down how to do that with both the free and paid version.

Overview

If you read part 1, you’ll know it was often possible to make 3.5 perform close to the level of 4. Fair warning before we get started, this is not possible for some of the more helpful aspects of using ChatGPT-4 for code. I’ll indicate a few uses for 3.5, but when we move into 4, I’ll illustrate why the investment is well worth it, and how 3.5 falls short.

Levering ChatGPT-3.5 for code

Boilerplate

ChatGPT-3.5 excels at outputting mundane but custom code. For example, a Vue template, but with several complications already integrated:

Me:

Output a Vue template for a NoteCard component. Control if it appears through the computed that checks both a shouldAppear prop, and that it has a Title and Description that isn’t null. It should optionally take a link, which won’t appear if there is no link destination, and says “Link” if no link text is supplied. Provide a mock API call in mounted that checks an endpoint to see if that endpoint has data. While the API call is in progress, loading must be set to true, and different styles applied while loading is true.

I’ll highlight what it does well and wrong below, you can check out the full code response at the end:

<template>
  <div class="note-card" v-if="shouldAppear && (title || description)">
    <div class="note-card-content">
      <h3>{{ title }}</h3>
      <p>{{ description }}</p>
      <a v-if="linkDestination" :href="linkDestination">{{ linkText || 'Link' }}</a>
    </div>
    <div class="note-card-loader" v-if="loading">
      <!-- Loading styles go here -->
      Loading...
    </div>
  </div>
</template>

<script>
export default {
  props: {
...
  },
  data() {
...
  },
  computed: {
    // Computed property to check if the card should appear
    isVisible() {
      return this.shouldAppear && (this.title || this.description);
    },
  },
  mounted() {
    if (this.linkDestination) {
      // Simulate an API call
      this.loading = true;
      ...
      }, 2000); // Simulate a 2-second API call
    }
  },
};
</script>

<style scoped>
...
</style>

The good:

  • It included everything I said
  • It auto-simulates a time-delay on the API call, so I could test how loading feels without needing to hook up the API

The bad:

  • It did not interpret my “loading means different styles” correctly
  • It doesn’t use the computed property “isVisible”, even though it has duplicate logic
  • I didn’t ask for styles besides maybe hinting at a placeholder for loading styles
  • A few Vue good practice violations

ChatGPT-4 did all of those things correctly with the first prompt, of course.

But a fix is easy. I prompted it:

Use the computed property, don’t duplicate the code. Don’t give me styles, just a placeholder for loading. Also, I want to change styles when loading is true, not have different DOM elements. Follow good Vue coding practices.

This rectified all of the major mistakes and made it nearly identical to ChatGPT-4’s output.

Questions

Method Help

For the most part, I’ve entirely quit endlessly searching documentation and who knows what else, as ChatGPT can tell me right away. For example:

Prompt: I’m using indexOf(‘six’) in Javascript to try and find where the word ‘six’ is in a string, but I want the last occurance, not the first.

ChatGPT-3.5:

The indexOf method in JavaScript only returns the index of the first occurrence of the specified substring within the given string. If you want to find the index of the last occurrence of ‘six’ in a string, you can use the following approach:

var str = “This is the first six. There is another six here. And the last six is here.”; var lastIndex = str.lastIndexOf(“six”); console.log(“Last occurrence of ‘six’ is at index: ” + lastIndex);

In this example, we use the lastIndexOf method instead of indexOf. It will search for the last occurrence of “six” in the string and return its index. The result will be the index of the last occurrence of “six” in the string.

I always recommend reading documentation when it comes to security, and in general I would suggest looking at documentation. However, small language nuances like the above example, and other mundane features are much more easily researched with ChatGPT.

Explain This Code

How obvious is it what this code is doing, right off the bat?

let options = props.options.map((locationNamePair, index) => {
  return (
    <Link href={locationNamePair[0]} key={index + locationNamePair[0]}>
      <a className={styles.optionsLink}>{locationNamePair[1]}</a>
    </Link>
  );
});

let mobileStructureOnClick = (
  <div className={styles.mobileLinks}>
      {options}
  </div>
)

The code names, and the filename being OptionsAccordion may help, but especially for a new React developer, some of the constructions and variable usage may be confusion. ChatGPT responds to “Can you explain this code to me?

ChatGPT-3.5:

Certainly! This code appears to be part of a React component and is used to generate a list of links based on the props.options array. Let me break it down step by step:

  1. let options = props.options.map((locationNamePair, index) => { ... });Here, you are mapping over the props.options array. It looks like props.options is an array of pairs, where each pair consists of a URL (locationNamePair[0]) and a display name (locationNamePair[1]). The .map() function is used to iterate over each pair in the array.Inside the .map() function, for each pair, a JSX element is created using the <Link> and <a> tags. The href attribute of the <Link> component is set to the URL (locationNamePair[0]), and the key attribute is set to the index plus locationNamePair[0] to uniquely identify each link element. The content of the link (<a>) is set to the display name (locationNamePair[1]), and it has a class name styles.optionsLink, which is likely used for styling purposes.
  2. let mobileStructureOnClick = ( <div className={styles.mobileLinks}> {options} </div> );Here, you are creating a JSX element mobileStructureOnClick. This element contains a <div> with the class name styles.mobileLinks, which is also likely used for styling. Inside this <div>, you are rendering the options variable.In other words, you are rendering the list of links generated earlier inside this <div>, and it will be displayed as a list of clickable options on your webpage.

Overall, this code dynamically generates a list of links based on the data in props.options and renders them inside a <div>, which is styled for mobile view. It’s a common pattern in React for rendering dynamic lists of elements based on data.

Summary

ChatGPT-3.5 is great for boilerplate, code explanations, syntax lookup, and even some mundane code editing.

Leveraging ChatGPT-4

ChatGPT-4 is senior developer who has not slept in several days. He will output quality code, knows the ins and outs of a language or system, and can provide high level feedback. You’ll want to fact check him though, maybe that lack of sleep caused him to mix some stuff up.

A quick demonstration of ChatGPT-4’s superiority, and proof of higher levels of knowledge:

Me:

I’m making a header component in react with Typescript, which will take dynamic numbers of JSX children. I need it to map over them and wrap them each in a button. The buttons will control whether or not panels show up below. Assume state is managed above the header, and the header just has access to an index setting it can call with the button clicks. Output just the component.

ChatGPT-3.5:

import React, { useState } from 'react';

interface HeaderProps {
  children: React.ReactNode[];
}

const Header: React.FC<HeaderProps> = ({ children }) => {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);

  const handleButtonClick = (index: number) => {
    setActiveIndex(activeIndex === index ? null : index);
  };

  return (
    <div>
      {React.Children.map(children, (child, index) => (
        <div key={index}>
          <button onClick={() => handleButtonClick(index)}>Toggle Panel {index + 1}</button>
          {activeIndex === index && child}
        </div>
      ))}
    </div>
  );
};

export default Header;

Fails:

  • Controls index in header, I said that was done in parent
  • I said a button wraps the child, this puts a div…and doesn’t wrap the child at all with the button
  • key={index} — The instructions said this was a dynamic list, so just using index here is inaccurate
  • this check: activeIndex === index && child is redundant

Not only does this get some key react features wrong, it would fail to work visually given the structure it decided on.

ChatGPT-4 (with React Expert):

import React, { ReactNode } from 'react';

interface HeaderProps {
  children: ReactNode[];
  onButtonClick: (index: number) => void;
}

const Header: React.FC<HeaderProps> = ({ children, onButtonClick }) => {
  return (
    <div>
      {children.map((child, index) => (
        <button key={index} onClick={() => onButtonClick(index)}>
          {child}
        </button>
      ))}
    </div>
  );
};

export default Header;

Fails: Same key mistake

ChatGPT-4, utilizing a publicly accessible GPT, manages to create almost exactly what I described, wrapping each child in a button, and outputting each button into a div, which presumably I could style to be the header container.

GPTs

The GPT store is ChatGPT-4’s other massive advantage over ChatGPT-3.5. GPTs allow you to pre-load custom prompts that drive the rest of the interaction, as well as custom data and API calls. For example, let’s design one that will not make that key mistake.

Custom Instructions

Do you have a set of standards you like to enforce on your code? With ChatGPT-3.5, you’ll have to paste these steps in each new chat, and in a chat where you exceed the context window (You’ve had too many back-and-forths and it doesn’t remember the first message anymore), it will also forget. ChatGPT-4 does not have this problem. A simplistic example:

Me:

I want all of my variables to be prefixed with “mxf_”. Anything I give you in this converstion, prefix it with “mxf_”. Here’s the first code:

ChatGPT-3.5:

Sure, here’s your code with the variables prefixed with “mxf_”:

let mxf_userName = 'John Doe';
const mxf_userId = 102;
var mxf_userStatus = 'active';

console.log('User Name:', mxf_userName);
console.log('User ID:', mxf_userId);
console.log('User Status:', mxf_userStatus);

mxf_userName = 'Jane Doe';
mxf_userStatus = 'inactive';

console.log('Updated User Name:', mxf_userName);
console.log('Updated User Status:', mxf_userStatus);

Now all variables are prefixed with “mxf_”.

 

Now here is that same code after sending it many, many messages:

ChatGPT-3.5:

The provided code is written in JavaScript and defines variables userName, userId, and userStatus. It then logs their values to the console and updates the values of userName and userStatus before logging the updated values.

Here’s a breakdown of the code: …

As you can see, it has forgotten the initial instruction. This problem doesn’t exist with ChatGPT-4’s GPTs. A simple instruction like this would be remembered for the whole chat:

Simple GPT

But, it gets better. Perhaps you have many different things you’d like to do, and perhaps they conflict with each other, or would result in a list of such dizzying length you would struggle to know what you’ve put in it. Or, maybe you’re working within a context of code you’ve already submitted — If you update a GPT, any existing chat with that GPT does not receive the update. How then, could one get their updated GPT to see their context without remaking the whole chat?

Well with ChatGPT-4, you can simply reference GPTs from within the chat! My bot, for example, could be called upon to clean up the code that default ChatGPT-4 creates:

Summon Another GPT

Above, I select the bot, Code Standard Bot. In the chat below, notice how it changes from ChatGPT to Code Standard Bot, and it implements the simplistic “mxf_” prefix I’d declared earlier.

Chat with GPTs and ChatGPT-4

This is so cool — imagine all the different ‘stored procedures’, if you will, that could exist across many different GPTs. All you have to do is summon them up in a single chat, forging code from idea to perfected reality.

Data Relevance and Internet

ChatGPT-4 is also internet connected and trained on more recent data. This means ChatGPT-4 better intuits responses from more recent data, and also Bing searches questions with obvious temporal aspects. For example:

Me:
What is the current version of react
ChatGPT-3.5:
As of my last update in January 2022, the latest stable version of React was 17.0.1. However, React is under active development, and newer versions may have been released since then. I recommend checking the official React website or the React GitHub repository for the most up-to-date information on the current version.

ChatGPT-4:

The current version of React is 18.2.0​​.

 

And, ChatGPT-4 provided a link.

This means ChatGPT-3.5 confidently answers incorrectly, while 4 seeks out the right information:

Me:
If I put multiple state updates inside a setTimeout, will it batch them?

ChatGPT-3.5:

No, automatic state batching won’t work as expected if you put it inside a setTimeout because setTimeout is asynchronous and runs outside of the React rendering cycle.

ChatGPT-4:

However, starting with React 18, React introduced a new feature called “automatic batching,” where state updates inside promises, setTimeout, native event handlers, or any other event are batched together.

Closing

ChatGPT has, in my opinion, become a staple of iterative development. Whether that’s pure information lookup and no code (due to security or other reasons), or the full-on copy+paste+build+repeat, the speed and accuracy that especially ChatGPT-4 can achieve, and the customization possible through GPTs, enables an insane increase in coding potential. I’m excited to see where these bots go, and what new features OpenAI builds next.

If you’re interested, check out my other blogs on ChatGPT, and stay tuned for more in this series!

Full Code Response

<template>
  <div class="note-card" v-if="shouldAppear && (title || description)">
    <div class="note-card-content">
      <h3>{{ title }}</h3>
      <p>{{ description }}</p>
      <a v-if="linkDestination" :href="linkDestination">{{ linkText || 'Link' }}</a>
    </div>
    <div class="note-card-loader" v-if="loading">
      <!-- Loading styles go here -->
      Loading...
    </div>
  </div>
</template>

<script>
export default {
  props: {
    shouldAppear: Boolean,
    title: String,
    description: String,
    linkDestination: String,
    linkText: String,
  },
  data() {
    return {
      loading: false,
    };
  },
  computed: {
    // Computed property to check if the card should appear
    isVisible() {
      return this.shouldAppear && (this.title || this.description);
    },
  },
  mounted() {
    if (this.linkDestination) {
      // Simulate an API call
      this.loading = true;
      setTimeout(() => {
        // Mock response from the API
        const apiResponse = {
          data: {
            // Add your API data properties here
          },
        };
        // Check if the API data is available
        if (apiResponse.data) {
          // Update the component data with the API data
          // Example: this.title = apiResponse.data.title;
          // this.description = apiResponse.data.description;
          this.loading = false; // Set loading to false when data is available
        } else {
          this.loading = false; // Set loading to false if API call fails
        }
      }, 2000); // Simulate a 2-second API call
    }
  },
};
</script>

<style scoped>
.note-card {
  border: 1px solid #ccc;
  padding: 20px;
  margin: 10px;
  background-color: #fff;
}
.note-card-content {
  margin-bottom: 10px;
}
.note-card-loader {
  /* Loading styles go here */
  background-color: #f0f0f0;
  text-align: center;
  padding: 10px;
}
</style>

 

]]>
https://blogs.perficient.com/2024/02/07/leveraging-chatgpt-for-professionals-part-2/feed/ 0 353216
How to Code Faster and Improve Your Productivity with TabNine https://blogs.perficient.com/2022/07/25/how-to-code-faster-and-improve-your-productivity-with-tabnine/ https://blogs.perficient.com/2022/07/25/how-to-code-faster-and-improve-your-productivity-with-tabnine/#respond Mon, 25 Jul 2022 18:49:47 +0000 https://blogs.perficient.com/?p=321910

One of the biggest things that a programmer/developer/coder wants to improve is his coding speed. This skill can be improved throughout the time while you are gaining experience.

Of course, many different tools allow you to “cheat” while you are coding; for example, Emmet is a plugin that provides you with some code snippets to improve your workflow by writing HMTL/CSS/JS code. Emmet is included by default in some code editors like VS Code, Atom, etc.

1 Emmet

Like Emmet,, there are a lot of plugins that provide you with different snippets for different programming languages such as Javascript, and PHP, or snippets for frameworks like React, Laravel, or Vue. These plugins can be different in each code editor or IDE, and in some cases, the plugins don’t exist or the functionalities are not the same.

2 PlugIns

What is TabNine?

TabNine is a powerful tool/plugin that allows you to code and deliver better code faster.

It accelerates development by providing code guidance with patterns learned from millions of repositories and your projects. This means that TabNine will understand what you are coding and will give you some suggestions to write code faster and automatically write parts of the code predicting your next block of code.

Let me give you an elementary example: I’m coding using Java and I am going to declare two variables, one of them is going to store the user’s name and the other is going to store the user’s password for an account.

Example 1

Look how I just declared the userName String and when I was writing the second variable, TabNine suggested the name userPassword for this variable. This is just a basic example of how TabNine works but it is very powerful.

Another example with the same code, now I am going to write the constructor of my Human class and look at what TabNine suggested. , It is amazing!

Example 2

TabNine supports all the programming languages and IDEs, and the best part of everything is that IT IS FREE!

5 TabNine

If you want to try TabNine, I’ll give you the official website link and the steps for installation. It is very easy, just follow this link 👉🏻 Code Faster with AI Code Completions

]]>
https://blogs.perficient.com/2022/07/25/how-to-code-faster-and-improve-your-productivity-with-tabnine/feed/ 0 321910
Using Windows PowerShell to Kick Off a OneStream Data Management Job https://blogs.perficient.com/2020/03/23/using-windows-powershell-to-kick-off-a-onestream-data-management-job/ https://blogs.perficient.com/2020/03/23/using-windows-powershell-to-kick-off-a-onestream-data-management-job/#respond Mon, 23 Mar 2020 20:24:54 +0000 https://blogs.perficient.com/?p=271738

Windows PowerShell is a shell scripting language often used in conjunction with Windows Task Scheduler for the automation of tasks and activities. Being able to automate tasks takes one more thing off an end-user’s plate. In this article, we will explore how to use Windows PowerShell to execute a data management job from OneStream. Data Management jobs in OneStream can be used to consolidate data, clear data, run a calculation, export data, kick off a business rule, and more.

Note: This script works only for clients not authenticating with SSO.

First, we initialize the OneStream Client API by adding the path to the OneStream API located in OneStream’s configuration files. Typically, the path listed below is where the API is located.

Add-Type -Path "C:\Program Files (x86)\OneStream Software\OneStreamStudio\OneStreamClientApi.dll"

Next, we declare a variable that contains the command to create an instance of the API.

$xfApi = new-object OneStream.Client.Windows.OneStreamClientApi

This part is used to log in and open the application (Note: This only works for OneStream native IDs. It will not work for Single-Sign-On). Here, we declare a variable that starts the instance of the API. In the script, you need to define the server address, OneStream user name, password, and application name.

$xfLogonInfo = $xfApi.Authentication.LogonAndOpenApplication("SERVER_ADDRESS", "OneStream_Username", "OneStream_Password", "OneStream_Application", [OneStream.Shared.Wcf.XFClientAuthenticationType]::ClearTextPW)

We run a loop to check if the application was successfully open. If it was, the console prints out that the login was successful. A new variable is then declared to execute the data management sequence. You need to define the name of the data management job and any parameters/variables here. If there are no parameters/variables, leave the second quotes empty, as shown below. Once the data management job is executed, you will get a message printed out in the console to let you know whether there was an error (typically on the OneStream side) or if it was executed successfully. The script then logs out of OneStream and closes out the API connection. If the application was not opened successfully, a message on why the application did not open will be printed in the console.

if ($xfLogonInfo.IsAppOpen) {
"Log in successful."
"Executing Data Management Sequence..."

$xfResult = $xfApi.DataManagement.ExecuteSequence("DataManagementJobName", "")
$xfResult.Message

$xfApi.Authentication.Logoff()
"Logged off."
}

else {
$xfLogonInfo.ErrorMessage
}

The completed code looks like this:

Add-Type -Path "C:\Program Files (x86)\OneStream Software\OneStreamStudio\OneStreamClientApi.dll"
$xfApi = new-object OneStream.Client.Windows.OneStreamClientApi
$xfLogonInfo = $xfApi.Authentication.LogonAndOpenApplication("SERVER_ADDRESS", "OneStream_Username", "OneStream_Password", "OneStream_Application", [OneStream.Shared.Wcf.XFClientAuthenticationType]::ClearTextPW)

if ($xfLogonInfo.IsAppOpen) {
"Logged on successfully."
"Executing Data Management Sequence..." 

$xfResult = $xfApi.DataManagement.ExecuteSequence("DataManagementJobName", "")
$xfResult.Message 

$xfApi.Authentication.Logoff()
"Logged off."
}

else {
$xfLogonInfo.ErrorMessage
}
]]>
https://blogs.perficient.com/2020/03/23/using-windows-powershell-to-kick-off-a-onestream-data-management-job/feed/ 0 271738
5 ways learning to code can improve your life https://blogs.perficient.com/2015/06/17/5-ways-learning-to-code-can-improve-your-life/ https://blogs.perficient.com/2015/06/17/5-ways-learning-to-code-can-improve-your-life/#respond Wed, 17 Jun 2015 13:18:58 +0000 http://blogs.perficient.com/perficientdigital/?p=8296

 
Image of scripting codeMy first crack at writing computer code came when computers were sofa-sized and the term “web” applied mainly to spiders. At my high school, programming was the alternative elective to woodworking and home economics. It wasn’t popular; throughout my four years there, I could count on my fingers and toes the total number of students who took the course.
Today, my grade-school-age nieces and nephews can field coding questions that eluded me until well past college, and each year the starting age of coders keeps sliding lower.
This is the new normal. Children who barely know how to tie their shoes are acquiring the literacy demanded by our increasingly digital world. Before this decade ends, a whole generation of educated Americans will pass from kindergarten through college without ever touching a pen or pencil, or a piece of paper.
Meanwhile, adults who raise these savvy students still lag in this key area of digital literacy two decades after the Internet dawned. Most are clueless about the code that shapes their world. This cluelessness is bracketed by reluctance and intimidation – at first glance, coding does not look easy, so obviously it isn’t easy, right?
On the contrary. Websites such as Codeacademy, Khan Academy, and W3Schools remove much of the guesswork with step-by-step tutorials and workspaces that show what the code displays as it’s typed. Apps including Hopscotch, Lightbot, and Udacity’s series of Android and iOS training tools cross age groups and knowledge levels and are designed to match the comfort level of each.
These user-friendly tools are making code approachable, even fun – much more fun than slogging through those disturbingly dense manuals that were the primary coding assets in my youth.
With that fun comes something else: an education that extends well beyond the scope of coding’s intent. Learning to code also promotes:
Literacy Software has become a linchpin in our lives. Many daily tasks – from watching TV to making toast to turning on a water faucet – rely on devices that in turn rely on software. While it’s not necessary for each of us to know exactly how coding operates any of these things, an appreciation for the analytical process that went into the software programming opens our minds to the way digital devices “think,” thus raising a broader digital awareness that enables us to make software more responsive.
Problem solving That analytical process derives from computational thinking, an approach to solving large problems by breaking them down into smaller ones. We’re introduced to this kind of thinking early in school to solve basic math problems and expand upon it later to tackle business, engineering, science, music, project management – anything that deals in abstractions. Learning code hones that thinking because it requires a systematic approach essential to problem solving.
Personal growth At first, my interest in learning to code was blunted by fear of failure (Everyone starts out writing bad code; it’s unavoidable). I dreaded the prospect of typing line after line of code only to see the wrong result – or worse, no result. This prompted me to code with care and check my work at each step. Of course, I still failed with predictable regularity, but I was slowly steeling myself against disappointment knowing the amount of care I exercised. Today’s code-training tools mitigate that kind of fear by showing results in real time. They don’t, however, mitigate the failure chronic to solution-based code writing; that comes from the exacting task of writing and rewriting the code until it’s correct.
Community Nobody I know who can code well learned by themselves. Sure, they sifted through manuals and guides at some point in their education. But the lasting lessons and best solutions to problems came through asking questions, working in groups, and studying others’ successes and failures. Despite the stereotypical image of the solitary coder hunched over a dusty keyboard, illuminated only by the screen’s glow, coding is a communal effort shared across a room or across a continent. So, it’s safe to say the best programs are developed with precise amounts of code and liberal amounts of collegiality. As content strategist Anthony Wing Kosner said, “Once you write something as code, others who can read code can evaluate it and see if you indeed have a unique idea that can generate value.”
Change – Digital awareness, critical and computational thinking, unwavering determination, and a willingness to reach out to others – these are qualities that effect change in an office, a business, an industry. The more we know about our digital world, the more likely we can make it more responsive, and more responsible. As with anything else, big changes start with the little details – such as learning how to write computer code.

]]>
https://blogs.perficient.com/2015/06/17/5-ways-learning-to-code-can-improve-your-life/feed/ 0 256957
Decoding the UI Architecture https://blogs.perficient.com/2015/06/10/decoding-the-ui-architecture/ https://blogs.perficient.com/2015/06/10/decoding-the-ui-architecture/#respond Wed, 10 Jun 2015 16:14:28 +0000 http://blogs.perficient.com/perficientdigital/?p=8265

With the increasing advent in SOA and RESTful based applications, all the business logic today is being pushed to the client. With numerable paradigms being present for the UI to consumes these services and create dynamic content, there becomes a need to define the presentation, structure and behavior of the User Interface.

While working with Brian Flanagan on a recent project, we came up with an architecture presentation to address this need, with an intent to help the business, customer, stakeholders and development team understand the architecture of UI/Front end development. 

UI Architecture

Presentation Layer

The Presentation Layer is mainly composed of CSS components, based out of an atomic design or BEM methodology. The CSS is typically written in either SASS or LESS (today’s most popular CSS pre-processors) and compiled to provide modular, scalable components, which is used to create the structural layer.

Structural Layer

Here, we create the html components/pages for the application, by making use of the structure today’s most popular frameworks provide – bootstrap, foundation and others, depending on the organization needs. The required user interactions are enhanced by making use of a JavaScript library, typically, jQuery. These HTML pages are then thoroughly tested for responsiveness, browser compatibility and accessibility. 

Behavioral Layer

The behavioral layer introduces the business logic for our UI by consuming the RESTful services and creating dynamic content. This could typically include two-way data binding, ajax, MVC and Single Page Applications, all rendered on the client.  There is an increasing number of frameworks to help us work with the business logic and the most popular one’s are Angular, Ember, Backbone, ReactJS among others. Note that selecting an appropriate framework is a very important task as each framework has its own pros and cons catering to different needs. 

Production Layer

Finally, we have a bunch of fantastic build tools that takes care of all the routine tasks involved in development such as compiling, minifying, compressing, package management, among others. The build tools keep a track of changes in all of the above 3 layers and eventually provides us production ready HTML, CSS and JavaScript assets which can now be integrated with any backend application.

I hope this article explains the UI architecture and the underlying processes. Is this something similar you have seen implemented in your project/organization ? Are things being done differently or do you have another perspective on this ? Do let us know below.

]]>
https://blogs.perficient.com/2015/06/10/decoding-the-ui-architecture/feed/ 0 256955
6 Ways to Overcome Programming Roadblocks https://blogs.perficient.com/2015/04/16/programming-roadblocks/ https://blogs.perficient.com/2015/04/16/programming-roadblocks/#respond Thu, 16 Apr 2015 15:43:48 +0000 http://blogs.perficient.com/perficientdigital/?p=7932

shutterstock_61202323Programmers, whether novice or professional, encounter roadblocks and issues every day while working with code. This can lead to unnecessary frustration, hamper productivity, and pose a threat to reaching the product deadline.
The following are a few measures that I, as a front-end developer, have developed to overcome roadblocks while working in fast-paced environments with stringent deadlines:
1. I am setting up my developer workspace. It is working for him but not for me.
Setting up a workspace can be one of the most tedious or scary tasks a developer encounters when he or she starts working on a new project. Set aside ample time for this, and do not be scared by the heavy stack of technical documentation. Follow each step meticulously, and make sure you have all the pre-requisites setup. Do not hesitate to take the help of a peer or your team lead if you come across a issue – be it simple or complex. Ultimately, having a proper workspace is the foundation for all the great work you are about to do on the new project.
2. My code is not working or it’s throwing up an error.
We encounter this issue almost every day. We would have gone through the requirement, analyzed the dependencies, made sure the functionality is there, and still the code does not work. Rather than simply blaming the code for throwing up an error, it is best to investigate why it is doing so. Check the browser console, error logs, stack trace. Often it could just be a spelling mistake or a syntax error causing the issue. Have a peer or your lead look over the codebase. A second eye helps in most instances. Do not lose hope, get frustrated, and start cursing your job or the client.
3. My jQuery on click function is not working.
As a front-end developer, you would be dealing with a lot of jQuery, and this issue is something we come across quite often. The blame is blandly put on jQuery or the browser itself. Rather, make use of breakpoints in the JavaScript console of your browser. Check if the code has been rendered on the page and if there are any errors in the console. Put appropriate the breakpoint and examine each step. A div id might be missing, could be a syntax error or even a missing semicolon. Breakpoints are your friend when it comes to javascript errors. Make use of them.
4. Clear browser cache.
We know this, but don’t do this. You have made change to a CSS file, and it is not reflecting on the browser. Always remember to clear your browser cache (It’s easy: Just press cmd+shift+del on your browser, check cached images and files and click Clear browsing data) for any new changes to be seen on the browser.
5. Know how to Google for error.
So you have checked the console logs, made sure there is no syntax error, cleared browser cache and still something doesn’t work – end of the world! Not really, as long as there is the Internet to help us out. Someone would have encountered this already and might have put a solution or the issue could be a well-known one. One important thing is to make sure how to make the best use of Google to help us fix errors. Search for the errors with meaningful phrases, such as ‘jQuery works in console, but not in code’, ‘bootstrap modal dialog function’ rather than simply searching for ‘jQuery is not working’ or ‘modal dialog issue.’ Another helpful measure is to search with the exact error message thrown in the console or error logs and often this might help us find a solution quickly.
6. Take breaks, and do not multitask.
Take adequate short breaks at regular intervals to regain your focus and keep up the concentration. If you have been looking at your computer screen for too long and you encounter an issue, chances are that you would end up stressed out or frustrated and lose focus. Hence, taking breaks is important. Secondly, we all think we can multitask, switch between different windows while drafting an email or checking one. We are actually not multi-tasking here. Rather, we are shifting the focus of our brain to different jobs in short intervals of time. This is bound to make you stressed out after a while and leave you feeling tired. It is best to focus on one job at a time, complete it, and then move on to the next to increase your productivity.
I hope these measures help you mitigate a roadblock when you are working with code every day. What are some of the measures you have been following? Share them below.

]]>
https://blogs.perficient.com/2015/04/16/programming-roadblocks/feed/ 0 256874
Client side Templating and Performance https://blogs.perficient.com/2015/03/19/client-side-templating-and-performance/ https://blogs.perficient.com/2015/03/19/client-side-templating-and-performance/#respond Thu, 19 Mar 2015 18:43:06 +0000 http://blogs.perficient.com/perficientdigital/?p=7551

A lot has been talked about client side view templates hindering the critical path, thus affecting performance. I have made an effort to summarize the need for client side rendering and measures to enhance the performance.

Before we actually jump on to measures, lets revisit how today’s web application ended up being rendered and compiled on the client (browser) using javascript based templates –

Before the advent of nodejs and javascript templates, how did one used to render json data on the browser ? 

Front end developers (FED) used to write prototypes based on html, css, jquery and hand this over to the backend developers. Backend devs take this asset and integrate it with the java code, parsing the json themselves directly in the servlet or jsp. Here, it takes only one call for the page to load and FED can focus on optimizing critical path, gzip the assets, etc thus improving the performance. This really worked well when we had only one or two FEDs for the whole project and a waterfall approach was followed. Designers used to provide the comps, UI developers created pixel perfect prototypes, and no design changes were allowed once the development started.

And then, what happened ?

Coming back to where we are today, as the web evolved, more focus is put on User Experience, and with the introduction of LeanUX, design and development are being done simultaneously. Now, backend developers cannot change the html in the jsp or servlet every time the design changes and becomes frustrating for them and they don’t see the need to do that at all. Enter jQuery and ajax. FEDs can make an ajax call to the RESTful service, parse the json and render it on the presentation layer, i.e jsp. But, this resulted in a convoluted mess of spaghetti code and became hard to maintain as the application grew. 

Same time, javascript became more mature and nodejs was introduced.  With the help of nodejs, enter client side templating – handlebars, mustache, htmlbars, etc. These templates are logic less (no if, else, for loop statements in the html) and provided a clear, neat separation of html and data paving the way for a true MVC architecture on the client. Both front end developers and back end devevelopers are happy as FEDs can focus on neat reusable, DRY html with dynamic data while backend developers can focus on generating the RESTful API service, data binding and need not worry about design changes at all. Because, data parsing is completely done on the browser now. To help with this data parsing and templating for the FEDs, a host of task runners to improve performance, based again on nodejs got introduced – grunt, gulp, etc. So that, FEDs can focus on the html and the task runner can do all the performance optimizations for them. Wonderful, isn’t it ?

So, what is the disadvantage of this client side templating ? 

With client side templating, every ajax call we make, there is an extra http call on the browser, and the template has to parse this data as well as render itself on the browser. Enter performance issues and critical path rendering.  

How to remediate ?

Fallback to nodejs for solutions again. Client side templating is still fairly new and as the web progresses, definitely the focus will be on ways to render the data on the server itself. There is already htmlbars, which is out to do that as mentioned herehere and also here.

Ultimately, the advantage of separating html from the backend code and allowing front end developers to make robust design changes concurrent with the development cycle has proved more advantageous, than the performance issues with the client side templating.

]]>
https://blogs.perficient.com/2015/03/19/client-side-templating-and-performance/feed/ 0 256866
Take the Plunge. Get Up to Speed with Front-End Build Tools https://blogs.perficient.com/2015/03/16/take-the-plunge-get-up-to-speed-with-front-end-build-tools/ https://blogs.perficient.com/2015/03/16/take-the-plunge-get-up-to-speed-with-front-end-build-tools/#respond Mon, 16 Mar 2015 19:53:20 +0000 http://blogs.perficient.com/perficientdigital/?p=7507

A colleague recently asked me to give him a high-level overview on how to get started using these fancy front-end build tools everyone’s talking about. Since I’m a team player, I thought it would be best to share my advice with all of you as well!
First, what the heck am I talking about? What are “front-end build tools”? Simply put, there is a community of people and a whole bunch of services out there who just want to make it easier for front-end developers to build projects. Their motivation? Why go through the hubbub of setting up your working directory structure, downloading the plugins and libraries you need, writing scripts for minification, etc., when all of that can be automated?  Enter the realm of build tools.
Now that you know what they do, how do you use them? I fully support the idea of learning by doing, so my job here is to introduce you to your new friends, and let you guys get to know each other on your own time. Have fun!
The Tool Trifecta

Node.js – https://nodejs.org/

First things first is Node.js. Node is the foundation for any front-end build tooling you want to do.  Many, many blog posts could be written on what Node can do, but for our purposes, it’s a means to use NPM (Node Package Manager) which you’ll use to install all the other things.

Grunt – http://gruntjs.com/getting-started

Grunt is a task runner that lets you automate a lot of your development process (minifying scripts, compiling SASS, watching for changes to files and reloading your page for you, etc). There is an alternate tool called Gulp that is gaining traction, but I still find that Grunt’s community is larger and better supported.

Bower – http://bower.io/

Another package manager that will download any assets you want / need for your particular project.  Most build tool generators will use Bower to get you set up.

Yeoman – http://yeoman.io/

Yeoman let’s you skip learning all the intricacies of building a Node / Grunt project from scratch and just use a build tool someone else already wrote.  Install Yo, then head over to the generators page (http://yeoman.io/generators/) to find one tailored to what your project needs are.

The appeal of build tools is that they should make your development process easier.  Yeoman and Bower make setting up your project at the start quicker, and Grunt makes your dev process easier throughout the life of your project.  You’ll excel if you really dive into Grunt and learn all that it can help you do. No task is too trivial!

And that about wraps it up. Get out there and start automating!

]]>
https://blogs.perficient.com/2015/03/16/take-the-plunge-get-up-to-speed-with-front-end-build-tools/feed/ 0 256865
Chrome DevTools Features to Help UI Development https://blogs.perficient.com/2015/02/18/chrome-devtools-features-to-help-ui-development/ https://blogs.perficient.com/2015/02/18/chrome-devtools-features-to-help-ui-development/#respond Wed, 18 Feb 2015 21:22:21 +0000 http://blogs.perficient.com/perficientdigital/?p=7203

In the technology industry, we often take for granted things in our work routine that we do so often we don’t even realize we’re doing them: keyboard shortcuts, program macros or any other “muscle memory” tasks that are second nature to us.  Many a time I have found myself working with a partner or helping a coworker with a bit of code and they stop me with a, “Whoa now, what the heck did you just do?”  For those people I’ve bullheadedly helped without helping, here is a short list of things you might not have known you could do with Chrome DevTools.

Android Debug Bridge

For starters, a few years ago I wrote a two-part article on how to use the Chrome DevTools to inspect and debug webpages from an Android device.  Pretty cool stuff, and useful when developing a responsive web design.

Force Element State

Another helpful feature is the ability to force states on any particular element in the DOM.  Do you need to debug the :hover styles of your main navigation, but can’t just leave your mouse hovering over it?  Pull up the DevTools, right click the element in question, then go to Force Element State.  You can have the browser mimic :active, :focus, :hover and :visited styles on any element.  This simple feature saves many a page reload.

Chrome DevTools Force Element State

Forcing an state on any element is just a right click away

Color Picker

The DevTools also have a color picker built into every CSS attribute that accepts a color value (color, background, border, etc).  In the Styles pane, right next to your color value it will show a small box that is filled with the color value you’ve specified.  That in itself is a handy feature to show you exactly what you’re specifying, but if you click that box it will launch a color picker that will let you extract any color from the entire page.  It’s your standard magnifying glass picker, so you can get right down to the pixel level with the color you’re choosing.  Great if you’re trying to match styles from one part of your page to another.

Chrome DevTools Color Picker

There is also a slider that lets you set the alpha level.

Console API

The last thing I want to share isn’t really a helpful feature as much as it is a “hey that’s pretty cool” feature.  In your JavaScript code, whenever you write out a console.log, you can style the text anyway you want by using the %c format specifier, and then passing it a string of CSS styles.  I guess if you wanted to show a certain error as GIANT RED TEXT then this would be useful, but other than that it’s just a fun way to make debugging less boring.

Chrome DevTools Console API

You can see more info about the Console API and all of the other neat things you can do with Chrome DevTools by checking out the documentation on their website.

Ref: the random CodePen I used in my screenshots

]]>
https://blogs.perficient.com/2015/02/18/chrome-devtools-features-to-help-ui-development/feed/ 0 256859
I&I musings – css, Apache, jQuery, web storage and LeanUX https://blogs.perficient.com/2014/09/16/ii-musings-css-apache-jquery-web-storage-and-leanux/ https://blogs.perficient.com/2014/09/16/ii-musings-css-apache-jquery-web-storage-and-leanux/#respond Tue, 16 Sep 2014 15:08:36 +0000 http://blogs.perficient.com/perficientdigital/?p=7035

CSS multi-language support

Chiuhua Chen, senior front end developer and prototyping expert at Perficient XD, is currently working on a web application that has a visual design supporting only english language. As with every other I&I Musingsproject, the business later on proposed support for multi-language support. When the application is in another language, spanish or Chinese, due to design constraints, the page appears messed up with some text occupying more width than what is actually allocated. On further research and checking with other peers, Chiu is working on implementing language specific stylesheet which would override the generic css file to take care of this issue. Lead front end developer Jacob Schulke has a few good points on the topic and has already shared his thoughts here. To learn more on how Chiu is tackling the multi-language css support issue, get in touch with her here.

Apache Virtual Hosts

Derek Montgomery, senior front end developer at Perficient XD, with a strong penchant for infrastructure setup and command line coding, is currently working on setting up a new virtual host for Perficient XD and doing further research on the topic, agrees that “If you have made a website, you have probably used Apache. One widely used application of virtual hosts is shared web hosting, whose prices are lower than a dedicated web server because many customers can be hosted on a single server”. He points out virtual hosts can potentially solve problems such as –

  • I have one domain (perficientxd.com), but I want multiple subdomains (e.g. dev., client., etc.).
  • I have one IP address available, but I need to test how multiple subdomains would function(use ports)!
  • Cost efficient, and pretty easy to configure and test.

To learn more on apache virtual host or if you are using them on your next project, shout out to Derek here. He is always there for everybody.

jQuery Best Practices

Harish Bhavanichikar, lead front end developer at Perficient XD, having worked on javascript, jQuery and other frameworks extensively on a number of projects shares some of the simple, easy to implement, effective best practices for the jQuery framework. He mentions how to do DOM manipulations the right way, handle events without event bubbling, clean ajax calls, check for deprecated methods and some general jQuery guidelines mentioned below –

  • Do not use jQuery 2.x if you are supporting IE 6/7/8.
  • Keep all your javascript and jQuery at the bottom of the page.
  • Do not load multiple jQuery versions.
  • If you are using other libraries like prototype, mootools, zepto, etc that uses $ as well, for jQuery functions simply use jQuery and return control of $ back to to the other library using $.noConflict()

The reference sheet can be accessed here.

HTML Web Storage

Jason Ripplinger, senior front end developer at Perficient XD, adept at integrating data with the presentation layer, tells us that HTML web storage is a great way to store the data locally in the browser, offering great advantages such as –

  • Uses less bandwidth –  cookies are sent with every HTTP header.
  • More secure – because the data is stored locally, the server has no direct access to it.
  • More storage room – cookies only allow 4096 bytes per cookie, web storage allows 5MB per domain.
  • Super easy to use – no plugins or libraries needed.

He further adds that web storage supports IE8 (did you know that ?) and data is stored as name-value pairs in strings and easily convertible to other formats. One best practice he suggests is to do a check to make sure the browser supports web storage before trying to access it and to use web storage only If there are no concerns about data being deleted. Get in touch with Jason here to learn more about how he has leveraged web storage in his current project.

IA, Visual Design and UI – LeanUX

Michael Gorgone, Senior Front End Developer at Perficient XD, with a keen interest and great knowledge on Information Architecture, opines that, “in most projects, by the time the IA is done and the wireframes are produced along with the visual design, we, the front end developers don’t seem to have much leeway to give feedback as to problems or issues they think could come up. Most cases, FEDs are not allowed to make any suggestions to the layout or where things could be improved without avoiding a confrontation with the visual design folks. Or the client has already approved the design and so changing it could cause a problem – business thinks the design is done but now it isn’t and has to be reworked. LeanUX is something geared towards helping with these issues. I think we need to have the IA, Visual Design and UI folks working together when the wireframes and Ixd is being done so that there is more collaboration and agreement as to what we have resulting in less re-work and more of a final product when it comes time to turn it into a prototype.” If you do not agree, or to discuss more, reach out to Michael here.

]]>
https://blogs.perficient.com/2014/09/16/ii-musings-css-apache-jquery-web-storage-and-leanux/feed/ 0 256784