• About Blog

    What's Blog?

    A blog is a discussion or informational website published on the World Wide Web consisting of discrete, often informal diary-style text entries or posts.

  • About Cauvery Calling

    Cauvery Calling. Action Now!

    Cauvery Calling is a first of its kind campaign, setting the standard for how India’s rivers – the country’s lifelines – can be revitalized.

  • About Quinbay Publications

    Quinbay Publication

    We follow our passion for digital innovation. Our high performing team comprising of talented and committed engineers are building the future of business tech.

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, February 10, 2021

Vue JS — Best Practices

 Vue JS Logo

VueJS — The Progressive JavaScript Framework

Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

If you are an experienced frontend developer and want to know how Vue compares to other libraries/frameworks, check out the Comparison with other Frameworks.

Lifecycle Hooks

Every Vue instance goes through a series of initialisation steps. When it is created from setting up data observation to compiling the template, to mounting the instance to the DOM, and finally to updating the DOM during data changes. This process is known as the lifecycle of a Vue instance and they have some functions run inside them by default as they go through this process of creating and updating the DOM. It is inside them that Vue components are created and manipulated, these functions are called lifecycle hooks.

There are eight lifecycle methods:

  1. Before Create
  2. Created
  3. Before Mount
  4. Mounted
  5. Before Update
  6. Updated
  7. Before Destroy
  8. Destroyed

If interested, take a look at  the Lifecycle Diagram of Vue JS. Refer to the official page which has complete details about each lifecycle hooks.

Be Aware of Camel vs Kebab Case

JavaScript are case-sensitive aka Counter is not equal to counter. As HTML, in general is case-insensitive, especially the HTML attributes. As VueJS spans both of these worlds, it’s better to understand this clearly.

camelCase

Start with lower-case and combine subsequent words by capitalise them. Example: amInCamelCase.

kebab-case

Write everything in lower-case and separate words by hyphens. Example: this-is-a-kebab-case.

To help you out, VueJS translates camelCase prop names into kebab-cased equivalent. But whenever things happen automatically, you need to be aware of it.

Vue.component('my-component', {
  props: ['myPropertyMessage'], // camelCase in JavaScript
  template: '<h1>{{myPropertyMessage}}</h1>'
})

The above JS code will translate to something like below

<!-- kebab-case in HTML -->
<my-component my-property-message="Hello World!"></my-component>

Hence declare props with camelCase and use Kebab Case in Templates.

Always use kebab-case for event names

When emitting/listening to custom events, we should always use kebab-case. Why? Because the events will be transformed automatically into lowercase anyway. We wont be listening to an event in camelCase or PascalCase, therefore, makes more sense to declare the event the same way we are going to listen to it: in kebab-case.

// Emitting
this.$emit('my-event') // instead of myEvent

// Listening
v-on:my-event

Always use :key in v-for loops

Is a common best practice to always add a :key to your template loops. A v-for without a :key can lead to hard to find errors, especially with certain kind of components or objects.

Don’t use v-if With v-for Elements

It’s a clear advice from the style guide from vuejs.org

<div v-for='plan in subscriptionPlans' v-if='plan.type == 1'></div>

The reason is that VueJS assigns a higher priority of the v-for than the v-if. This leads to a performance issue as the loop would run and filter inside instead of filter first.

The best practice here is to reduce the size to iterate over before the iteration by using a computed property:

computed: {
  onSaleSubscriptions: function() {
    return this.subscriptionPlans.filter(function (plan) {
       return(plan.type == 1)
    })
  }
}

Use $_ for mixins properties

Mixins are a great way to get repeated code into one single block and import it as many times as you want, but this can lead to several issues. In this point we will address the issue of overlapping properties.

When we import a mixin into our Component we are merging the mixin code with our component code. Now what happens with property that have the same name? Component will always have the upper hand as their properties have higher priority.

What if I want my mixin to have more priority? You can’t assign a priority but you can avoid properties from overlapping or even from overwriting by choosing a correct naming convention.

In order to differentiate mixin properties from Component properties we use $_. Why these symbols? Well, several reasons:
  • Convention from VueJs style guide
  • _ is reserved for Vue’s private properties
  • $ is reserved for Vue’s ecosystem

var authMixin = {
   //...
   methods: {
      $_authMixinGetUserInfo(){
         //...
      }
   }
}

Clear event listeners on component destroy with $off

When listening to events with $on, we should always remember to remove that listener with $off on destroyed(). This prevents us from having memory leaks.

const EmployeeComponent = { 
  mounted() {
    console.log("Employee component mounted");
    this.notify.$on("manager", this.startedListening);
  },
  beforeDestroy() {
    console.log("Employee component before destroy");
    // Remove all listening events.
    this.notify.$off("manager", this.stoppedListening);
  },
  methods: {
    startedListening() {
      // callback
    },
    stoppedListening() {
      // callback
    },
  },
};

Sources:


Friday, January 15, 2016

Minification of JS/CSS

Image of HTML/CSS/JS
Image Source: https://webinlinedev.com/

Minification is a process of compressing the source code, without changing it’s functionality. This technique is useful sometimes, specially in the case of a web application with huge JavaScript/CSS files. In other cases, it’s probably just a micro-optimization. Minifying JavaScript/CSS files reduces the bandwidth used and also improves the performance of the application as the page loading time is minimal.

As per Wikipedia Source:

Minified source code is especially useful for interpreted languages deployed and transmitted on the Internet (such as JavaScript/StyleSheet), because it reduces the amount of data that needs to be transferred. Minified source code may also be used as a kind of obfuscation. In Perl culture, aiming at extremely minified source code is the purpose of the Perl golf game.

Minified source code is also very useful for HTML/CSS code. As an example, successive whitespace characters in HTML/CSS are rendered as a single space, so replacing all whitespace sequences with single spaces can considerably reduce the size of a page.

If you are using Maven for your build process, then you can use Minify Maven Plugin which is a wrapper above the YUI Compressor and Google Closure Compiler but has a layer of abstraction around these tools which allows for other tools to be added in the future.

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-war-plugin</artifactId>
   <version>2.4</version>
   <configuration>
      <warSourceExcludes>/styles/*.css,/scripts/*.js</warSourceExcludes>
   </configuration>
</plugin>

<plugin>
   <groupId>com.samaxes.maven</groupId>
   <artifactId>minify-maven-plugin</artifactId>
   <version>1.7.2</version>
   <executions>
   <execution>
   <id>minify</id>
   <phase>process-resources</phase>
   <goals>
      <goal>minify</goal>
   </goals>
   <configuration>
      <charset>utf-8</charset>
      <jsEngine>CLOSURE</jsEngine>
      <skipMerge>true</skipMerge>
      <nosuffix>true</nosuffix>
      <cssSourceDir>styles</cssSourceDir>
      <cssTargetDir>styles/minified</cssTargetDir>
      <cssSourceIncludes>
         <cssSourceInclude>*.css</cssSourceInclude>
      </cssSourceIncludes>
      <jsSourceDir>scripts</jsSourceDir>
      <jsTargetDir>scripts/minified</jsTargetDir>
      <jsSourceIncludes>
         <jsSourceInclude>*.js</jsSourceInclude>
      </jsSourceIncludes>
   </configuration>
   </execution>
   </executions>
</plugin>

I created a sample web application with “scripts” folder to store javascript files and “styles” folder to store stylesheet files and used the above configuration to test the Minification process.

I copied the latest version of certain JavaScript and StyleSheet files weighed as noted below:

  • script/category-app.js –> 636 B
  • script/jquery.js –> 273199 B
  • styles/style-foundation.css –> 44659 B

After the Maven build, the minified versions of JavaSript and StyleSheet files weighed as noted below:

  • script/category-app.js –> 256 B
  • script/jquery.js –> 94689 B
  • styles/style-foundation.css –> 37016 B

The above results show that the Minification process is working well as expected. So, if you are using a lot of JavaScript/StyleSheet files in your web application, consider minifying your js/css code, so that you can reduce the data transferred and also improve the performance of your web application. In some cases, it might be a micro-optimization.

I have added the configuration <skipMerge>true</skipMerge>. Hence you see that all your files are minified but kept under the same file name within the minified folders respectively. If you set the value to <skipMerge>false</skipMerge>, then it merges all your JavaScript/StyleSheet files into one single file.

If the configuration <nosuffix>true</nosuffix>, you see that all the file names still remain same as the original ones. If you set the value ot <nosuffix>false</nosuffix>, then it will suffix all your JavaScript/StyleSheet file names with ‘.min’.

For more detailed information about the plugin, please click here.


Featured Post

Your AI Sidekick: How Claude took over Pritee’s Repetitive tasks

  It was a classic Wednesday morning in our Bengaluru office . Pritee, one of our sharpest Project Managers, had just stepped out of a stake...