top of page

Observer APIs in JavaScript — Part II

We already discussed Mutation observers and Intersection observers in the above article. Let’s continue with the next.

This article is the continuation of the previous part. If you didn’t read the below article I suggest that to read. Because It will be helpful to understand about Observers APIs.

You can find the first part here.

We already discussed Mutation observers and Intersection observers in the above article. Let’s continue with the next.

Resize Observer:

Resize Observer is used to observing changes to DOM Element’s size. It waits for the changes being made to the target element size.

Resize Observer Flow Diagram


When Resize Observer triggers:

  1. Target element inserted or removed from the DOM.

  2. Target element display property set to none.

  3. Target element size changes.

Resize observers will not notifies us in the below scenarios.

  1. CSS Transforms happens.

  2. For non-replaced inline Elements.


Concepts:


Key Concepts


We have learned more about the above concepts in the previous article. We are already familiar with these concepts. So it is easy to implement resize observers.

Use Cases:

  1. Modify the DOM elements while element size changes. (i.e) we can change CSS properties such as color, background, and so on.

  2. Manipulate the DOM elements such as adding or removing elements while element size changes.

We can use Resize Observer wherever we want to track DOM Elements size that is the core concept of resize Observer.

As always, Let’s take one use-case from the list. I am going to modify the DOM element when target element size change.

Modify the DOM elements while target size changes:


The above codepen is a very simple example of a resize observer. Let see step by step.

Step: 1 Setup the Basic UI Logics:

The below screenshot is the UI output of the codepen example.

Resize Observer example — UI


Step: 2 Create a Resize Observer:

Create a resize observer object and set the target for that observer.

const box = document.querySelector('.box'); 
//Target 
const resizeObserver = new ResizeObserver(entries => 
//Resize observer creation   
console.log(entries); }); 
let connect = () => {   
resizeObserver.observe(box); 
//start resizeObserver 
}); 
let disconnect = () => {   
resizeObserver.unobserve(box); 
//stop resizeObserver   
resizeObserver.disconnect(); 
//stop all resizeObservers 
});<>

I have created the resize Observer object here. ‘box’ is the target element of the observer. connect and disconnect methods start and stop resize observers respectively. Let see the output in the console.

Console:

Console Output


The resize observer notifies when the target element size changes. Here, we can see the details about the target element. We can use any of these details such as borderBoxSize, contentBoxSize, contentRect, and so on.

Step: 3 Add DOM modification logic inside Callback:


const resizeObserver = new ResizeObserver(entries =>{ 
//Add Logic Here 
});<>

As always, We have two buttons in UI that are “ connect” and “disconnect”. If we click the connect button observe(target) method will trigger. So the observer will start to watch the target element.

When the target size changes callback will trigger. So, DOM modification logic will run. There is no complex logic here. I just add and remove CSS style property background color.

Step: 4 Disconnect Observer:

let disconnect = () =>{       
observer.unobserve(box); 
//Stop observer.     
observer.disconnect(); 
//Stop all observers. 
}<>

We can disconnect an observer by calling the ‘unobserve()’ method or we can use the disconnect() method, It will disconnect all observers at once.

Output:


Resize observer output


That’s it. very simple, right? Just try it in your projects, it will be very helpful.

Note: Actually, We can achieve this use-case without a resize observer. Here, we can manage with input change event itself. But, let assume another scenario, just try to change browser screen size. It will work for that scenario also. Yes, We have a method called ‘window.resize()’ in javascript. Using this method we can track viewport size changes. Using that we can try to find element size changes. But it takes lots of effort and code logic. Similarly, It triggers each and every viewport size changes. It leads to performance issues. So resize observer is the best way to track element size changes.

If you know some different kinds of use cases just leave it in the comment. That will be really helpful for all.

Performance Observer:

The performance observer interface observes performance entries (that are useful to measure the performance) such as mark, measurement, navigation, resource, and so on. If any entries change, the performance observer notifies us.

The above definition might be confusing because performance entry is a new term for some of us. So let’s know some basics in performance APIs.

Performance API:

Measuring performance is one of the important things in web applications. Because everyone wants their web application to be faster. Performance APIs are very useful to measure web performance. There are many interfaces in performance APIs.

Performance Observer Flow Diagram


Performance Timeline API:

Performance Timeline API extends the Performance interface which have three methods. Those are getEntries(), getEntriesByName(), getEntriesByType(). These methods returns performance entries. Performance Entries:

The things we measure using performance APIs referred to as Performance Entries. Those are listed out in the above diagram. Performance Entries will be directly created by calling mark() or measure() methods. Performance entries are also created in indirect ways such as loading a resource(image).

Performance Observers observe exactly these performance entries. If any entry added or removed, it will notify us.

A performance observer is one of the interfaces of the performance API. It is just an added feature in the performance API. However, we are going to focus only on performance observer API.

Concepts:


Concepts


Use Case:

  1. We can track performance entities, deliver more accurate data to performance analytic tools.

  2. Track javascript elapsed time for script logics or loops.

We can use Performance Observer wherever we want to track performance entries that is the core concept of performance Observer.

Track elapsed time for loops:


Step: 1 Setup the Basic UI Logics:

The below screenshot is the UI output of the codepen example.

Performance Observer Example — UI


Step: 2 Create a Performance Observer:

Create a Performance observer object and set the entry types that need to observe.

var observer = new PerformanceObserver(list => 
{   
console.log(list.getEntries()); 
});  
observer.observe({entryTypes: ['resource', 'mark', 'measure']}); //start observer  
performance.mark('start'); 
for(let i=0; i<1000;i++){   
console.log('print'); 
}  
performance.mark('end'); 
function markDone() {   
performance.mark('done'); 
}  
performance.measure('start to end', 'start', 'end'); 
function disconnect(){   
observer.disconnect(); 
//disconnect observer }
<>

Here, I have created two mark methods. One is before the ‘for’ loop and another one is after the loop ends. After that, I have created a measure() method. That will calculate the elapsed time.

Step: 3 Disconnect Observer:


function disconnect(){       
observer.disconnect(); 
//disconnect observer }
<>

As always, We can disconnect observers by calling the ‘disconnect()’ method.

Output:


So, we did it!. Similarly, we can find elapsed time for service calls, events, and so on.

Conclusion:

Observer APIs are very helpful. Those will decrease our effort and reduce unwanted code and logic.

  1. Mutation Observer — Mutation Observer observes the DOM tree.

  2. Intersection Observer — An intersection observer observes the DOM element’s visibility and positions

  3. Resize Observer — Resize Observer is used to observing changes to DOM Element’s size.

  4. Performance Observer — Performance Observer observes performance entries.

Thanks for observing about observers APIs.


Source: InDepth.dev

0 comments
bottom of page