<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lachezar Nickolov on Medium]]></title>
        <description><![CDATA[Stories by Lachezar Nickolov on Medium]]></description>
        <link>https://medium.com/@lsnickolov?source=rss-7bf063b56732------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rejGwCS_qE-QOlee-6OGIg.jpeg</url>
            <title>Stories by Lachezar Nickolov on Medium</title>
            <link>https://medium.com/@lsnickolov?source=rss-7bf063b56732------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 16:20:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lsnickolov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Just launched: Session segmentations based on session and user criteria]]></title>
            <link>https://medium.com/sessionstack-blog/just-launched-session-segmentations-based-on-session-and-user-criteria-2702e14a4c0b?source=rss-7bf063b56732------2</link>
            <guid isPermaLink="false">https://medium.com/p/2702e14a4c0b</guid>
            <category><![CDATA[product-updates]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[sessionstack]]></category>
            <dc:creator><![CDATA[Lachezar Nickolov]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 16:10:48 GMT</pubDate>
            <atom:updated>2021-04-29T16:10:48.959Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last couple of months, our team has been working hard on a completely new segmentations functionality that will allow you to find the sessions you need quickly and accurately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXCw3jfN526LodxJJn9o5Q.png" /></figure><p>The newly-introduced segmentations functionality allows you to specify which fields you want to search by. Additionally, depending on the type of field, you get different comparison operators. For example, if the field is of type string, you can search for all sessions where this field contains some substring, or it matches completely, and so on.</p><p>And last but not least, the segmentations will allow you to include custom user fields defined through our <a href="https://docs.sessionstack.com/reference#identify">SessionStack.identify API</a>. With the API, you can set custom fields of type integer, real number, string, date, or boolean. Each type has its own comparison operators. For example, if you have a custom field named “Signed up” and it is of type date, you can search for all users who have signed up before a specific date.</p><h4><strong>Coming up next</strong></h4><p>This is only the beginning. The segmentations functionality will soon be extended with more features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ievcoy3RCx1DH4qqbLfc6g.png" /></figure><p>One of them will be the ability to build fine-grained filters by combining the search terms with both “or” and “and” operators.</p><p>Additionally, you will be able to save your segments. This update will allow you to have quick access to your most frequently searched sessions. On top of that, those segments will be accessible to all team members added to the project, which will also make collaboration easier.</p><p>Another new feature in the works is the ability to combine the currently available search terms with events that have occurred throughout the session. This functionality will allow you to define specific workflows in your product/website and find the sessions based on what the users are doing.</p><p>We would love to hear your feedback. Let us know what you’d like to see next in SessionStack.</p><p>If you still haven’t had the chance to try out SessionStack, get your free trial. It’s free for 14 days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3E3VSolyDZdxbo-bapMExg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2702e14a4c0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/just-launched-session-segmentations-based-on-session-and-user-criteria-2702e14a4c0b">Just launched: Session segmentations based on session and user criteria</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pausing session recording, blocking bots, and user permissions in the latest SessionStack update]]></title>
            <link>https://medium.com/sessionstack-blog/pausing-session-recording-blocking-bots-and-user-permissions-in-the-latest-sessionstack-update-f2afd10459e2?source=rss-7bf063b56732------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2afd10459e2</guid>
            <category><![CDATA[user-management]]></category>
            <category><![CDATA[session-recording]]></category>
            <category><![CDATA[sessionstack]]></category>
            <category><![CDATA[googlebot]]></category>
            <category><![CDATA[product-updates]]></category>
            <dc:creator><![CDATA[Lachezar Nickolov]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 16:24:45 GMT</pubDate>
            <atom:updated>2021-01-11T16:24:45.302Z</atom:updated>
            <content:encoded><![CDATA[<p>In the past months, SessionStack has rolled out several new features. Their main focus is to let you record more relevant sessions and make the most out of your monthly sessions quota.</p><h3>Pause session recording per project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yD5ymC6ENAPVw4_zbxXdQ.png" /></figure><p>SessionStack is rather flexible in terms of when and how the session recording starts. It can start automatically once your app/website is loaded, when a specific page is visited, or manually after a specific user action by using our JavaScript API. And sometimes you need to stop the recording for a specific project. Now you can disable it with a single flip of a switch. This allows you to keep your current project settings, avoid code changes, and flip it back again once you want for the recording to continue.</p><h3>Block Google bots</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zmj8YJwGZaHkRcZXz7PrIQ.png" /></figure><p>Indexing bots these days are rather sophisticated and can simulate an actual user. They load your app/website in a similar environment to ensure that it’s rendered properly and crawl through the pages to extract all the relevant information needed for them to be indexed. This of course can lead to having recorded sessions from such bots. SessionStack can now be enabled to block Google bots and save your monthly sessions quota for the relevant sessions.</p><h3>Disable project settings editing for team members (on-premises only)</h3><p>Sometimes you need to ensure that users from your team cannot modify the settings of your SessionStack projects and only a select few to be able to do this. Exactly this is now available for on-premises deployments of SessionStack. The access and update of project settings can be disabled for read-only users and be available only for admin users.</p><p>We would love to hear your feedback and suggestions. Let us know what you’d like to see next in SessionStack.</p><p>And if you still haven’t had the chance to try out SessionStack, <a href="https://app.sessionstack.com/signup">sign up</a> for a trial. It’s free for 14 days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3E3VSolyDZdxbo-bapMExg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2afd10459e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/pausing-session-recording-blocking-bots-and-user-permissions-in-the-latest-sessionstack-update-f2afd10459e2">Pausing session recording, blocking bots, and user permissions in the latest SessionStack update</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: Under the hood of custom elements + Best practices on building reusable…]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c?source=rss-7bf063b56732------2</link>
            <guid isPermaLink="false">https://medium.com/p/e118e888de0c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[how-javascript-works]]></category>
            <dc:creator><![CDATA[Lachezar Nickolov]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 15:51:51 GMT</pubDate>
            <atom:updated>2023-04-27T13:42:47.641Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How JavaScript works: Under the hood of custom elements + Best practices on building reusable components</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*2oRILfJJtmW07mbK" /></figure><p>This is post # 19 of the series dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-custom-elements">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><p>If you missed the previous chapters, you can find them here:</p><ul><li><a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">An overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-classes-and-inheritance-transpiling-in-babel-and-113612cdc220">The internals of classes and inheritance + transpiling in Babel and TypeScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-storage-engines-how-to-choose-the-proper-storage-api-da50879ef576">Storage engines + how to choose the proper storage API</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">The internals of Shadow DOM + how to build self-contained components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-webrtc-and-the-mechanics-of-peer-to-peer-connectivity-87cc56c1d0ab">WebRTC and the mechanics of peer to peer connectivity</a></li></ul><p><strong>Overview</strong></p><p>In <a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">one of our previous posts</a> we discussed the Shadow DOM API and a few other concepts which are all parts of a bigger picture — web components. The whole idea behind the web components standard is to be able to extend the built-in capabilities of HTML by creating small, modular, and reusable elements. It’s a relatively new W3C standard that has already been approved by all major browsers and can be seen in production environments… of course with the help of a polyfill library (which we’re going to talk about later in the post).</p><p>As you might already know, the browser provides us with a few very important tools for building websites and web applications. We’re talking about HTML, CSS and JavaScript. You use HTML for structuring your application, CSS to make it look beautiful, and JavaScript to bring the action. However, before web components were introduced there was no easy way to associate JavaScript behavior to the HTML structure.</p><p>In this post we’re going to get to the foundations of web components — custom elements. In a nutshell the custom elements API allows you to create (as the name suggests) custom HTML elements with built-in JavaScript logic and CSS styles. Many people confuse custom elements with shadow DOM. But they are two completely different concepts and they’re actually complementary instead of interchangeable.</p><p>Some frameworks (e.g. Angular, React) try to solve the same problem by introducing their own concepts. You can compare the custom elements to Angular’s directives or React’s components. However, custom elements are native to the browser and require nothing more than vanilla JavaScript, HTML, and CSS. Of course, this doesn’t mean necessarily that it’s a replacement for a typical JavaScript framework. Modern frameworks give us more than just being able to simulate the behavior of custom elements. So the two can work side by side.</p><p><strong>API</strong></p><p>Before we dive in, let’s take a quick look over what the API actually looks like. The customElements global object gives you a few methods:</p><ul><li>define(tagName, constructor, options) — Defines a new custom element. Takes three arguments: A valid tag name for a custom element, class definition for the custom element, and an options object. Only one option is supported currently: extends which is a string specifying the name of a built-in element to extend. Used to create a customized built-in elements.</li><li>get(tagName) — Returns the constructor of a custom element if the element is defined and returns undefined otherwise. Takes a single argument: A valid tag name for a custom element.</li><li>whenDefined(tagName) — Returns a promise which is resolved once a custom element is defined. If the element is already defined, it will be resolved immediately. The promise is rejected if the tag name is not a valid custom element name. Takes a single argument: A valid tag name for a custom element</li></ul><p><strong>How to create a custom element</strong></p><p>Creating a custom element is actually a piece of cake. You need to do two things: Create a class definition for the element which should extend the HTMLElement class and register that element under a name of your choice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d13763c2a04dfcc81b77eccdb88f1bb2/href">https://medium.com/media/d13763c2a04dfcc81b77eccdb88f1bb2/href</a></iframe><p>Or if you want, you can use anonymous class in case you don’t want to clutter the current scope</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49a7d47426d00ada3f14e19f43b63f3c/href">https://medium.com/media/49a7d47426d00ada3f14e19f43b63f3c/href</a></iframe><p>As you can see from the examples, custom elements are registered by using the customElements.define(...) method.</p><p><strong>What issues are custom elements solving</strong></p><p>So what’s the problem actually. <strong>Div soups</strong> are part of it. What is a div soup you might ask — it’s a very common structure in modern web apps where you have multiple nested div elements (div inside a div inside a div and so on).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/392708081628e9c6f814456872e5c4fc/href">https://medium.com/media/392708081628e9c6f814456872e5c4fc/href</a></iframe><p>This kind of structure is used since it makes the browser render the page as it should. However, it makes the HTML unreadable and very hard to maintain.</p><p>So for example we might have a component which is supposed to look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/0*v56OyrPtg_cZzzaZ" /></figure><p>And traditionally the HTML might look like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fea2bb023ad16e4d78226d1ac56fbda3/href">https://medium.com/media/fea2bb023ad16e4d78226d1ac56fbda3/href</a></iframe><p>But imagine if we could make it look like this instead</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e69001d8efec0b3a363104f1af907be7/href">https://medium.com/media/e69001d8efec0b3a363104f1af907be7/href</a></iframe><p>The second example is much better, if you ask me. It’s more maintainable, readable, and it makes sense both for the browser and the developer. It’s just simpler.</p><p>The other issue is reusability. Our job as developers requires not only to write working code but also a maintainable one. And one thing that makes some code maintainable is being able to easily reuse a piece of code instead of writing it again and again.</p><p>I’ll give you a simple example but you’ll get the idea. Let’s say we have the following element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c75ceac8b50b44df8d2f982f14d610/href">https://medium.com/media/35c75ceac8b50b44df8d2f982f14d610/href</a></iframe><p>If we need to use this elsewhere we’d need to write the same HTML all over again. Now imagine that we need to do a change that needs to apply to each of those elements. We’d need to find each place in the code and do the exact same change again and again. Bummer…</p><p>Wouldn’t it be better if we could just do the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6fc672dc7bcf39e301e64d2dd05364f/href">https://medium.com/media/c6fc672dc7bcf39e301e64d2dd05364f/href</a></iframe><p>But a modern web application is not just static HTML. You need to interact with it. And this comes from the JavaScript. Usually, what you might do is create some elements and then attach whatever event listeners you need in order for them to react to the input of the user. Whether they’re clicked, dragged, hovered and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d47bee49aaa666528c1a075d06799f3a/href">https://medium.com/media/d47bee49aaa666528c1a075d06799f3a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e972a79c0b0a19d5acf4ee27c6f6e52/href">https://medium.com/media/0e972a79c0b0a19d5acf4ee27c6f6e52/href</a></iframe><p>With the custom elements API all this logic can be encapsulated into the element itself. The example below does exactly the same as the one above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96d8d22f012a7bbbf408a2642f52401/href">https://medium.com/media/d96d8d22f012a7bbbf408a2642f52401/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf72a4584804a873a5b50ccd5367525d/href">https://medium.com/media/bf72a4584804a873a5b50ccd5367525d/href</a></iframe><p>At first it may seem like the custom elements approach requires more lines of JavaScript. But in a real-life application you rarely have this kind of scenario where you create a single element which is not reused. One more thing which is typical for modern web apps is that most elements are created dynamically. So you’d need to handle separate cases for when the element is added dynamically using JavaScript or it’s defined previously in the HTML structure. And you get all of this out of the box with custom elements.</p><p>So to summarize, custom elements make your code easier to understand and maintain, and splits it into small, reusable and encapsulated modules.</p><p><strong>Requirements</strong></p><p>Now before you go on and create your first custom element, you should know that there are special rules that must be followed.</p><ul><li>The name <strong>must</strong> contain a dash (-) in it. This way the HTML parser can tell which elements are custom and which are built-in. It also ensures that there won’t be a name collision with built-in elements (either now or in the future when other ones are added). For example, &lt;my-custom-element&gt; is a valid name while &lt;myCustomElement&gt; and &lt;my_custom_element&gt; are not.</li><li>Registering the same tag name more than once is forbidden. This will cause the browser to throw a DOMException. You cannot override custom elements.</li><li>Custom elements cannot be self-closing. The HTML parser allows only a handful of built-in elements to be self-closing (e.g. &lt;img&gt;, &lt;link&gt;, &lt;br&gt;) .</li></ul><p><strong>Capabilities</strong></p><p>So what actually can you do with custom elements? And the answer is — many things.</p><p>One of the best features is that the class definition of the element is actually referring to the DOM element itself. This means that you can use this directly to attach event listeners, access its properties, access child nodes, and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34780c259caa15a6b3a2892c26a01414/href">https://medium.com/media/34780c259caa15a6b3a2892c26a01414/href</a></iframe><p>This, of course, gives you the ability to overwrite the child nodes of an element with new content. But this is generally not recommended, since it might lead to unexpected behavior. As a user of a custom element that’s not implemented by yourself you will be surprised if your own markup inside the element is replaced by something else.</p><p>There are a few hooks that you can define for executing code at specific times of the element’s lifecycle.</p><p>constructor</p><p>The constructor is called once the element is created or upgraded (we’ll talk about this in a bit). It’s most commonly used for state initialization, attaching event listeners, creating a shadow DOM, etc. One thing to keep in mind is that you should always call super() in the constructor.</p><p>connectedCallback</p><p>The connectedCallback method is called each time the element is added to the DOM. It can be used (it’s also recommended) to delay some work until the element is actually on the page (e.g. fetching a resource).</p><p>disconnectedCallback</p><p>Analogous to connectedCallback, the disconnectedCallback method is called once an element is taken out of the DOM. Usually used for freeing up resources. One thing to have in mind is that the disconnectedCallback is never called if the user closes the tab. So be careful what you’re initializing in the first place.</p><p>attributeChangedCallback</p><p>This method is called once an attribute of the element has been added, removed, updated or replaced. It’s also called once the element is being created by the parser. However, note that this applies only for attributes which are whitelisted in the observedAttributes property.</p><p>addoptedCallback</p><p>The addoptedCallback method is called once the document.adoptNode(...) method is called in order to move it to a different document.</p><p>Note that all of the callbacks above are synchronous. For example, the connected callback is called immediately after the element is added to the DOM and nothing else happens in the meantime.</p><h4>Property reflection</h4><p>Built-in HTML elements provide one very handy capability: property reflection. This means that the values of some properties are directly reflected back to the DOM as an attribute. Such example is the id property.</p><p>myDiv.id = &#39;new-id&#39;;</p><p>Will also update the DOM to</p><p>&lt;div id=&quot;new-id&quot;&gt; ... &lt;/div&gt;</p><p>And it applies in the opposite direction as well. This is very useful since it allows you to configure elements declaratively.</p><p>Custom elements don’t get this kind of functionality out of the box but there is a way to implement it on your own. In order to achieve the same behavior in our custom elements we can define getters and setters for the properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a700adee151dfa3939ed907642c95de5/href">https://medium.com/media/a700adee151dfa3939ed907642c95de5/href</a></iframe><h4>Extending elements</h4><p>The custom elements API allows you not only to create new HTML elements but to also extend existing ones. And it works perfectly fine both for built-in elements and other custom ones. And it’s done just by extending its class definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e9017aa18254a94ef5f683c521b72d/href">https://medium.com/media/74e9017aa18254a94ef5f683c521b72d/href</a></iframe><p>Or in the case of built-in elements we need to also add a third parameter to the customElements.define(...) function which is an object with a property extends and a value the tag name of the element that’s being extended. This tells the browser which element exactly is being extended since many built-in elements share the same DOM interface. Without specifying which element exactly you’re extending, the browser won’t know what kind of functionality is being extended.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae9f9b747eaac055843bcab88e7f45d2/href">https://medium.com/media/ae9f9b747eaac055843bcab88e7f45d2/href</a></iframe><p>An extended native element is also called a customized built-in element.</p><p>What you can use as a rule of thumb is to always extend existing elements. And do this progressively. This allows you to keep all of the previous features (properties, attributes, functions).</p><p>Note that customized built-in elements are only supported by Chrome 67+ right now. It will be implemented in the other browsers as well but Safari has chosen not to implement it at all.</p><p><strong>Upgrading elements</strong></p><p>As mentioned above, we use the customElements.define(...) method to register a custom element. But this doesn’t mean that it’s the first thing that you have to do. Registering a custom element can be postponed for some time in the future. Even after the element itself is added to the DOM. This process is called element upgrade. To let you know when the element is actually defined, the browser provides you the customElements.whenDefined(...) method. You pass it the tag name of the element it returns a promise which is resolved once the element is registered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5d667c49325c731c847cbd5117035ef/href">https://medium.com/media/d5d667c49325c731c847cbd5117035ef/href</a></iframe><p>For example, you might want to delay something until all child elements are defined. Which can be really useful if you have nested custom elements. Sometimes the parent element might rely on the implementation of its children. In this case, you need to make sure that the child elements are defined before their parent.</p><h4>Shadow DOM</h4><p>As we already said, custom elements and shadow DOM are meant to be together. The former is used to encapsulate JavaScript logic into an element while the latter is used to create an isolated environment for a piece of DOM which is not affected by the outside world. I suggest you check out <a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">one of our previous blog posts</a> devoted to shadow DOM to get a much better understanding of the concept.</p><p>And to use shadow DOM for your custom element you simply need to call this.attachShadow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9beafc6ef3007c7fac02644577f0a23f/href">https://medium.com/media/9beafc6ef3007c7fac02644577f0a23f/href</a></iframe><h4>Templates</h4><p>We’ve briefly talked about templates in <a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">one of our previous posts</a> and they alone deserve a post of their own. Here we’re going to give a simple example how you can incorporate templates into the creation of your custom elements. Using the &lt;template&gt; you can declare a DOM fragment tag which is parsed but not rendered on the page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82aa48a0b1cf3dd34c9fcbb3ca8c3445/href">https://medium.com/media/82aa48a0b1cf3dd34c9fcbb3ca8c3445/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ce109d346b72f568d0bdc230d42b17/href">https://medium.com/media/d2ce109d346b72f568d0bdc230d42b17/href</a></iframe><p>So now that we have combined custom elements with shadow DOM and templates we get an element which is isolated in its own scope and has a nice separation of the HTML structure and the JavaScript logic.</p><p><strong>Styling</strong></p><p>So we went through the HTML and JavaScript but what about CSS. Obviously, we need a way to style our elements. We can add CSS stylesheets inside the shadow DOM but then you might ask how do we style the elements from the outside as users of the element. And the answer is simple — you style them the same way as you do with built-in elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4a2a2db87aadbfe77e46f0888ce1a25/href">https://medium.com/media/f4a2a2db87aadbfe77e46f0888ce1a25/href</a></iframe><p>Note that a style defined from the outside is with a higher priority and it will override the style defined from the element.</p><p>You know how sometimes you can actually see the page render and you see for a brief moment some flash of unstyled content (FOUC). You can avoid this by defining styles for undefined components and use some kind of transition when they become defined. To do this you can use the :defined selector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a238b73d6d636ced77995d8d2695b0fe/href">https://medium.com/media/a238b73d6d636ced77995d8d2695b0fe/href</a></iframe><h4>Unknown elements vs undefined custom elements</h4><p>The HTML specification is very flexible and allows declaration of whatever tag you want to. And if the tag is not recognized by the browser it will be parsed as HTMLUnknownElement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91b5d82fe08fd1e5c2bea9ba450ef3a4/href">https://medium.com/media/91b5d82fe08fd1e5c2bea9ba450ef3a4/href</a></iframe><p>However, this does not apply for custom elements. Remember when we talked that there are specific naming rules for defining custom elements? The reason is that if the browser sees a valid name for a custom element it will parse it as an HTMLElement and is considered by the browser to be an undefined custom element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe9ccf5820cb073046d5e3e1f804d84/href">https://medium.com/media/3fe9ccf5820cb073046d5e3e1f804d84/href</a></iframe><p>While there might not be any visual differences between the HTMLElement and HTMLUnknownElement there are other things to keep in mind. They are treated differently by the parser. An element with a valid custom element name is expected to have a custom implementation. And until that implementation is defined it’s treated just like an empty div element. While an undefined element does not implement any method or property of any built-in element.</p><h4>Browser support</h4><p>The first version of custom elements was introduced in Chrome 36+. It was the so called custom components API v0 which is now deprecated and considered a bad practice although still available. Although, if you want to learn more about v0 you can read about it in this <a href="https://www.html5rocks.com/en/tutorials/webcomponents/customelements/">blog post</a>. The custom elements API v1 is available since Chrome 54 and Safari 10.1 (although partially). Microsoft’s Edge is in its prototyping phase and Mozilla has it since v50 but it’s not available by default and needs to be enabled explicitly. At the moment only webkit browsers support it fully. However, as mentioned above, there’s a polyfill that allows you to use custom elements across all browsers. Yes, even IE 11.</p><h4>Checking for availability</h4><p>To make sure that the browser supports custom elements you can do a simple check whether the customElements property exists in the window object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fb62d64b81053d6c9801944b23b4c7f/href">https://medium.com/media/7fb62d64b81053d6c9801944b23b4c7f/href</a></iframe><p>Or in case you’re using the polyfill library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9175b58773954a4edd8c9c5b1d835a7/href">https://medium.com/media/c9175b58773954a4edd8c9c5b1d835a7/href</a></iframe><p>So to summarize, the custom elements part of the web components standard gives you the following:</p><ul><li>Associating JavaScript behavior and CSS styling to an HTML element</li><li>Allows you to extend already existing HTML elements (both built-in and other custom ones)</li><li>Requires no library or framework to get you started. You just need vanilla JavaScript, HTML and CSS and optionally a polyfill library in order to support older browsers.</li><li>It’s built to work seamlessly with other web components features (shadow DOM, templates, slots, etc.)</li><li>Tightly integrated with the browser’s dev tools.</li><li>Leverage existing accessibility features.</li></ul><p>Custom elements are not that different from what we’ve been using until now after all. It’s just another way to make things more convenient while developing web apps. So it opens up the possibility to build very complex apps at a faster pace. But the higher the complexity the higher the chance of introducing an issue that’s hard to track down and reproduce. That’s why debbuging them requires more context and a tool like SessionStack makes a difference.</p><p>SessionStack gets integrated into into web apps to collect data such as user events, network data, exceptions, debug messages, DOM changes, and so on, and to send this data to our servers.</p><p>After that, the collected data is processed in order to create a <a href="https://www.sessionstack.com/blog/what-is-customer-experience-analytics-improve-product-strategy/">video like experience</a> so you can see your users interacting with your product. This, alongside all of the technical information SessionStack provides, gives you the ability to reproduce issues you’ve never been able to track down before.</p><p>So in order to ensure that SessionStack will always produce pixel perfect session replay we need to keep up with the arising technologies, frameworks, and web standards.</p><p>There is a free plan if you’d like to <a href="https://www.sessionstack.com/solutions/developers?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-custom-elements">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*CVp6bG3I04pVEFSa" /></figure><p>References:</p><ul><li><a href="https://developers.google.com/web/fundamentals/web-components/customelements">https://developers.google.com/web/fundamentals/web-components/customelements</a></li><li><a href="https://www.html5rocks.com/en/tutorials/webcomponents/customelements/">https://www.html5rocks.com/en/tutorials/webcomponents/customelements/</a></li><li><a href="https://github.com/w3c/webcomponents/">https://github.com/w3c/webcomponents/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e118e888de0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c">How JavaScript works: Under the hood of custom elements + Best practices on building reusable…</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8?source=rss-7bf063b56732------2</link>
            <guid isPermaLink="false">https://medium.com/p/abfcf7e8a0c8</guid>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Lachezar Nickolov]]></dc:creator>
            <pubDate>Thu, 24 May 2018 17:21:22 GMT</pubDate>
            <atom:updated>2023-04-27T13:44:32.352Z</atom:updated>
            <content:encoded><![CDATA[<p>This is post # 14 of the series dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-parsing-intro">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><p>If you missed the previous chapters, you can find them here:</p><ul><li>A<a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">n overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li></ul><h3>Overview</h3><p>We all know how things can get messy ending up in one big blob of JavaScript. Not only does this piece of code need to be transferred over the network but it also has to be parsed, compiled into bytecode, and finally executed. In the previous posts, we discussed topics such as the JS engine, runtime, and the call stack, as well as the V8 engine that’s mainly used by Google Chrome and NodeJS. They all play a vital role in the whole JavaScript execution process. The topic we’re planning to introduce today is no less important: we’ll see how most JavaScript engines parse text into something that’s meaningful to the machine, what happens after, and how we as web developers can turn this knowledge to our advantage.</p><h3>How programming languages work</h3><p>So let’s take a step back and look at how programming languages work in the first place. No matter what programming language you’re using you’ll always need some piece of software which can take the source code and make the computer actually do something. This software can be either an interpreter or a compiler. No matter whether you’re using an interpreted language (JavaScript, Python, Ruby) or a compiled one (C#, Java, Rust), there’s always going to be one common part: parsing the source code as plain text to a data structure called abstract syntax tree (AST). Not only do ASTs present the source code in a structured way but they also play a critical role in the semantic analysis where the compiler validates the correctness and proper usage of the program and the language elements. Later on, the ASTs are used to generate the actual bytecode or machine code.</p><h3>AST applications</h3><p>ASTs are not only used in language interpreters and compilers. They have multiple applications in the computer world. One of the most common ways to use them is for static code analyzing. Static analyzers don’t execute the code that’s given to their input. Still, they need to understand the structure of the code. For example, you may want to implement a tool that finds common code structures, so that you can refactor them to reduce duplication. You might be able to do this by using string comparison, but the implementation will be very basic and limited. Naturally, if you’re interested in implementing such a tool you don’t need to write your own parser. There are many open source implementations which are fully compatible with the Ecmascript specifications. Esprima and Acorn, to name a couple. There are also many tools that can help with the output produced by the parser, namely the ASTs. ASTs are also used widely in implementing code transpilers. So for example you might want to implement a transpiler which converts Python code to JavaScript. The basic idea is that you would use a Python transpiler to generate an AST which you would then use to generate back JavaScript code. You might ask, how is this even possible. The thing is that ASTs are just a different way of representing some language. Before the parsing it’s represented as text which is following some rules which make up a language. After the parsing it’s represented as a tree structure which contains exactly the same information as the input text. Therefore, we can always do the opposite step and go back to a textual representation.</p><h3>JavaScript parsing</h3><p>So let’s see how an AST gets built. We have a simple JavaScript function as an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef6af2c15d3403fbc2f89b931f2b511e/href">https://medium.com/media/ef6af2c15d3403fbc2f89b931f2b511e/href</a></iframe><p>The parser will produce the following AST.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*mSOIiWpkctkD0Gfg." /></figure><p>Note that for visualization purposes, this is a simplified version of what the parser would produce. The actual AST is much more complex. The idea here, however, is to get a feel for what would be the first thing that would happen to the source code before it gets executed. If you want to see what the actual AST looks like, you can check <a href="https://astexplorer.net/">AST Explorer</a>. It’s an online tool in which you pass some JavaScript and it outputs the AST for that code.</p><p>Why do I need to know how the JavaScript parser works, you might ask. After all, it should be the browser’s responsibility to make it work. And you are right, sort of. The below graph shows the total time allocation to the different steps in the JavaScript execution process. Take a close look and see if you find anything interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eEArxn147Ev8xf5n." /></figure><p>Did you see it? Take a closer look. On average, it takes a browser roughly 15% to 20% of the total execution time to parse the JavaScript. I didn’t come up with the numbers. These are stats from real-world applications and websites which utilize JavaScript one way or another. Now 15% might not seem a lot to you, but trust me, it is. A typical SPA loads about 0.4MBs of JavaScript and it takes the browser approximately 370ms to parse it. Again, you might say, well, that’s not that much. It’s not a lot by itself. Bear in mind though that this is only the time needed to parse the JavaScript code into ASTs. This doesn’t include the execution itself or any of the rest of the processes taking place during a page load such as <a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">CSS and HTML rendering</a>. And this all refers to desktop only. Once we go into mobile, things quickly get more complicated. <em>Time spent on parsing can often be two to five times as much on phones as on desktop.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3R6-AyKY1831P10d." /></figure><p>The above graph shows the parsing time of 1MB bundle of JavaScript across mobile and desktop devices of different class.</p><p>What’s more, web apps are getting more complex by the minute as more business logic is going to the client side to introduce a more native-like user experience. You can easily understand how much this is affecting your app/website. All you need to do is open the browser dev tools and let it measure the amount of time spent on parsing, compiling, and everything else that’s happening in the browser until the page is fully loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*A5ucCHOZsxXyHMfN." /></figure><p>Unfortunately, there are no dev tools on mobile browsers. No worries though. This doesn’t mean that there’s nothing you can do about it. This is why tools like <a href="https://github.com/danielmendel/DeviceTiming">DeviceTiming</a> exist. It can help you measure parsing &amp; execution times for scripts in a controlled environment. It works by wrapping local scripts with instrumentation code so that each time your pages are hit from different devices you can locally measure the parsing and execution times.</p><p>The good thing is that JavaScript engines do a lot to avoid redundant work and get more optimized. Here are a few things that engines do across major browsers.</p><p>V8 for example does script streaming and code caching. Script streaming means that async and deferred scripts get parsed on a separate thread as soon as the download has begun. This indicates that the parsing is almost immediately done after the script is downloaded. It results in pages getting loaded about 10% faster.</p><p>The JavaScript code is usually compiled into bytecode on each page visit. This bytecode, however, is then discarded once the user navigates to another page. This happens because the compiled code depends a lot on the state and context of the machine at the time of compilation. This is where Chrome 42 introduces bytecode caching. It’s a technique which stores the compiled code locally so when the user gets back to the same page all steps such as download, parsing and compiling can be skipped. This allows Chrome to save about 40% on parsing and compilation time. Plus, this also results in saving mobile devices’ battery life.</p><p>In Opera, the <a href="https://dev.opera.com/blog/carakan/">Carakan</a> engine can reuse the compiler output from another program that was recently compiled. There’s no requirement that the code should be from the same page or even domain. This caching technique is actually very effective and can skip the compilation step entirely. It relies on typical user behavior and browsing scenarios: whenever the user follows a certain user journey in the app/website, the the same JavaScript code gets loaded. However, the Carakan engine has been long replaced by Google’s V8.</p><p>The <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> engine used by Firefox doesn’t cache everything. It can transition into a monitoring stage where it counts how many times a given script is being executed. Based on this count it determines which parts of the code are hot and need to be optimized.</p><p>Obviously, some take the decision not to do anything. <a href="http://en.wikipedia.org/wiki/Maciej_Stachowiak">Maciej Stachowiak</a>, the lead developer of Safari, states that Safari doesn’t do any caching of the compiled bytecode. It’s something that they have considered but they haven’t implemented since the code generation is less than 2% of the total execution time.</p><p>These optimizations do not directly affect the parsing of the JavaScript source code but they definitely do their best to completely skip it. What can be a better optimization than not doing it altogether?</p><p>There are many things we can do to improve the initial loading time of our apps. We can minimize the amount of JavaScript we’re shipping: less script, less parsing, less execution. To do this we can deliver only the code required on a specific route instead of loading one big blob of everything. For example, the <a href="https://developers.google.com/web/fundamentals/performance/prpl-pattern/">PRPL</a> pattern preaches this type of code delivery. Alternatively, we can check our dependencies and see if there’s anything redundant that might be doing nothing more but bloating our codebase. These things deserve a topic of their own, however.</p><p>The goal of this article is to discuss what we as web developers can do to help the JavaScript parser do its job faster. And there is. Modern JavaScript parsers use heuristics to determine whether a certain piece of code is going to be executed immediately or its execution will be postponed for some time in the future. Based on these heuristics the parser will do either eager or lazy parsing. Eager parsing runs through the functions that need to be compiled immediately. It does three main things: builds AST, builds scope hierarchy, and finds all syntax errors. Lazy parsing, on the other hand, is used only on functions that don’t need to be compiled yet. It doesn’t build an AST and it doesn’t find all syntax errors. It only builds the scope hierarchy which saves about half the time compared to the eager evaluation.</p><p>Clearly, this is not a new concept. Even browsers like IE 9 support such type of optimization albeit in a rather rudimentary way compared to the way today’s parsers work.</p><p>So let’s see an example of how this works. Say we have some JavaScript which has the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a74eeab6c8693b743372aa40bb128106/href">https://medium.com/media/a74eeab6c8693b743372aa40bb128106/href</a></iframe><p>Just like in the previous example, the code is fed into the parser which does syntactic analysis and outputs an AST. So we have something along the lines of:</p><p>Function declaration of <em>foo</em> which accepts one argument (x). It has one return statement. The function returns the result of the + operation over x and 10.</p><p>Function declaration of <em>bar</em> which accepts two arguments (x and y). It has one return statement. The function returns the result of the + operation over x and y.</p><p>Make a function call to bar with two arguments 40 and 2.</p><p>Make a function call to console.log with one argument the result of the previous function call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*60xiqW7kPsQg5ssn." /></figure><p>So what just happened? The parser saw a declaration of the foo function, a declaration of the bar function, a call of the bar function and a call of the console.log function. But wait a minute… there’s some extra work done by the parser that’s completely irrelevant. That’s the parsing of the foo function. Why is it irrelevant? Because the function foo is never called (or at least not at that point in time). This is a simple example and might look like something unusual but in many real-world apps, many of the declared functions are never called.</p><p>Here instead of parsing the foo function, we can note that it’s declared without specifying what it does. The actual parsing takes place when necessary, just before the function is executed. And yes, the lazy parsing still needs to find the whole body of the function and make a declaration for it, but that’s it. It doesn’t need the syntax tree because it’s not going to be processed yet. Plus, it doesn’t allocate memory from the heap which usually takes up a fair amount of system resources. In short, skipping these steps introduces a big performance improvement.</p><p>So in the previous example, the parser would actually do something like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*IN688nPbgu8zYETe." /></figure><p>Note that the foo function declaration is acknowledged but that’s it. Nothing more has been done to go into the body of the function itself. In this case, the function body was just a single return statement. However, as in most real-world applications, it can be much bigger, containing multiple return statements, conditionals, loops, variable declarations and even nested function declarations. And this all would be a complete waste of time and system resources since the function will never be called.</p><p>It’s a fairly simple concept but in reality, its implementation is far from being simple. Here we showed one example which is definitely not the only case. The entire method applies to functions, loops, conditionals, objects, etc. Basically, everything that needs to be parsed.</p><p>For example, here’s one pretty common pattern for implementing modules in JavaScript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b59d81898d8ff88d25b022cfd156977/href">https://medium.com/media/1b59d81898d8ff88d25b022cfd156977/href</a></iframe><p>This pattern is recognized by most modern JavaScript parsers and is a signal that the code inside should be parsed eagerly.</p><p>So why don’t parsers always parse lazily? If something is parsed lazily, it has to be executed immediately, and this will actually make it slower. It’s going to make a single lazy parse and another eager parse right after the first one. This will result in a 50% slowdown compared to just parsing it eagerly.</p><p>Now that we have a basic understanding of what’s happening backstage, it’s time to think about what we can do to give the parser a hand. We can write our code in such a way so that the functions are parsed at the right time. There’s one pattern which is recognized by most parsers: wrapping a function in parenthesis. This is almost always a positive signal for the parser that the function is going to be executed immediately. If the parser sees an opening parenthesis and immediately after that a function declaration, it will eagerly parse the function. We can help the parser by explicitly declaring a function as such that is going to be executed immediately.</p><p>Let’s say we have a function named foo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/337df6833a94ca89a30596f094b16db9/href">https://medium.com/media/337df6833a94ca89a30596f094b16db9/href</a></iframe><p>Since there’s no obvious sign that the function is going to be executed immediately the browser is going to do a lazy parse. However, we’re sure that this is not correct so we can do two things.</p><p>First, we store the function in a variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc31f5486480e2aab91fce4592765ae1/href">https://medium.com/media/bc31f5486480e2aab91fce4592765ae1/href</a></iframe><p>Note that we left the name of the function between the function keyword and the opening parenthesis before the function arguments. This is not necessary but is recommended since in the case of a thrown exception the stacktrace will contain the actual name of the function instead of just saying &lt;anonymous&gt;.</p><p>The parser is still going to do a lazy parse. This can be prevented by adding one small detail: wrapping the function in parenthesis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49d242ee9c3195747a7d9a0057fdd72d/href">https://medium.com/media/49d242ee9c3195747a7d9a0057fdd72d/href</a></iframe><p>At this point, when the parser sees the opening parenthesis before the function keyword it’s going to do immediately an eager parsing.</p><p>This can be rather difficult to manage manually as we’ll need to know in which cases the parser will decide to parse the code lazily or eagerly. Also, we’d need to spend time thinking whether a certain function will be invoked immediately or not. We surely don’t want to do this. Last but not least, this is going to make our code harder to read and understand. To help us do that, tools like Optimize.js come to the rescue. Their sole purpose is to optimize the initial loading time of the JavaScript source code. They do static analysis of your code and modify it in such a way that the functions that need to be executed first are wrapped in parenthesis so that the browser can eagerly parse them and prepare them for execution.</p><p>So we’re coding as usual and there’s a piece of code that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec2625e07537c92882c4881098dc9ce/href">https://medium.com/media/bec2625e07537c92882c4881098dc9ce/href</a></iframe><p>Everything seems fine, working as expected and it’s fast because there’s an opening parenthesis before the function declaration. Great. Of course, before going into production, we need to minify our code to save bytes. The following code is the output of the minifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/253b039ad99cc7a8ad11275b9f9ffc34/href">https://medium.com/media/253b039ad99cc7a8ad11275b9f9ffc34/href</a></iframe><p>It seems ok. The code works as before. There’s something missing though. The minifier has removed the parenthesis wrapping the function and instead has placed a single exclamation mark before the function. This means that the parser is going to skip this and will do a lazy parse. On top, to be able to execute the function it will do an eager parse right after the lazy one . This all makes our code run slower. Luckily, we have tools like Optimize.js that do the hard work for us. Passing the minified code through Optimize.js is going to produce the following output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0709193870467b4eefad927682701b20/href">https://medium.com/media/0709193870467b4eefad927682701b20/href</a></iframe><p>That’s more like it. Now we have the best of both worlds: the code is minified and the parser is properly identifying which functions need to be parsed eagerly and which lazily.</p><h3><strong>Precompilation</strong></h3><p>But why can’t we do all this work on the server side? After all, it’s much better to do it once and serve the results to the client rather than forcing each client do the job every time. Well, there’s an ongoing discussion whether engines should offer a way to execute <em>precompiled</em> scripts so this time isn’t wasted in the browser. In essence, the idea is to have a server-side tool that can generate bytecode which we’d only need to transfer over the wire and execute it on the client-side. Then we’d see some major differences in start-up time. It might sound tempting but it’s not that simple. This might have the opposite effect since it would be larger and most probably would need to sign the code and process it for security reasons. The V8 team , for example, is working on internally avoiding reparsing so that precompiling might not actually be that beneficial.</p><h3>A few tips that you can follow to serve your app to users as fast as possible</h3><ul><li>Check your dependencies. Get rid of everything that’s not needed.</li><li>Split your code into smaller chunks instead of loading one big blob.</li><li>Defer the loading of JavaScript when possible. You can load only the required pieces of code based on the current route.</li><li>Use dev tools and DeviceTiming to find out where the bottleneck is.</li><li>Use tools like Optimize.js to help the parser to decide when to parse eagerly and when lazily.</li></ul><p>SessionStack is a tool that recreates visually everything that happened to the end users at the time they experienced an issue while interacting with a web app. The tool doesn’t reproduce the session as an actual video but rather simulates all the events in a sandboxed environment in the browser. This brings some implications, for example in scenarios where the codebase of the currently loaded page becomes big and complex.</p><p>The above techniques are something that we recently started to incorporate in SessionStack’s development process. Such optimizations allow us to load SessionStack faster. The faster SessionStack can free the browser resources the more seamless, natural user experience the tool will offer when loading and <a href="https://www.sessionstack.com/blog/kpis-customer-success-teams-digital-analytics-examples/">watching user sessions</a>.</p><p>There is a free plan if you’d like to <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=parsing-and-abstract-syntax-trees">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*h2Z_BnDiWfVhgcEZ." /></figure><h4>Resources</h4><ul><li><a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">https://en.wikipedia.org/wiki/Abstract_syntax_tree</a></li><li><a href="https://medium.com/@jotadeveloper/abstract-syntax-trees-on-javascript-534e33361fc7">https://medium.com/@jotadeveloper/abstract-syntax-trees-on-javascript-534e33361fc7</a></li><li><a href="https://medium.com/reloading/javascript-start-up-performance-69200f43b201">https://medium.com/reloading/javascript-start-up-performance-69200f43b201</a></li><li><a href="https://timkadlec.com/2014/09/js-parse-and-execution-time/">https://timkadlec.com/2014/09/js-parse-and-execution-time/</a></li><li><a href="https://www.youtube.com/watch?v=Fg7niTmNNLg">https://www.youtube.com/watch?v=Fg7niTmNNLg</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abfcf7e8a0c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">How JavaScript works: Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recording user sessions in closed environments: hybrid mobile and desktop apps, and browser…]]></title>
            <link>https://medium.com/sessionstack-blog/recording-user-sessions-in-closed-environments-hybrid-mobile-and-desktop-apps-and-browser-d164d1c17a67?source=rss-7bf063b56732------2</link>
            <guid isPermaLink="false">https://medium.com/p/d164d1c17a67</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[hybrid-apps]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[customer-experience]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Lachezar Nickolov]]></dc:creator>
            <pubDate>Thu, 15 Jun 2017 14:14:11 GMT</pubDate>
            <atom:updated>2017-11-02T12:22:53.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recording user sessions in closed environments: hybrid mobile and desktop apps, and browser extensions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*wv7035gDrfHiWYtlmRITEA.png" /></figure><h3>The components of the non-web JavaScript app</h3><p>We are all well aware of the building blocks of the modern website/web app:</p><ul><li>HTML defines the structure and textual content of the page</li><li>CSS states the page look and feel</li><li>JavaScript determines page behavior</li><li>Other static resources like images, fonts, videos, etc. enrich overall user experience</li></ul><p>These, however, are also the integral parts of browser extensions, hybrid mobile applications (e.g. <a href="https://cordova.apache.org/">Cordova</a>-based ones), as well as <a href="https://electron.atom.io/">Electron</a>-based desktop applications (or alternatives to the Electron framework).</p><p>The beauty of it is that developers can reuse their web tech skills to craft hybrid mobile and desktop apps, or even browser plugins: tools like Cordova and Electron play the role of a bridge between the web and native/desktop technology. Cordova applications, for example, “execute within wrappers targeted to each platform and rely on standards-compliant API bindings to access each device’s capabilities such as sensors, data, and network status. The application itself is implemented as a web page that references CSS, JavaScript, images, media files, or other resources necessary for it to run.” (See <a href="https://cordova.apache.org/">Cordova’s docs</a> for more details on app architecture)</p><p>Electron, on the other hand, is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS, as well as various Node libraries. The interface container is handled by Chromium and uses a bundled Node.JS server to “serve” the app within the container. (<a href="https://electron.atom.io/">See more</a> on building apps with Electron)</p><p>A browser extension can be authored using web technologies too. Chrome extensions, for example, are just simple web apps that run in a little page that appears when the user clicks the icon. The only difference is that an extension requires a manifest file to define the structure, permissions, icons and other metadata. (<a href="https://medium.com/@aidobreen/building-a-simple-chrome-extension-1b8a0fca3ca6">Check out Aidan Breen’s blog post</a> on building Chrome extensions.)</p><h3>The challenges cross-platform tools bring to tracking user behavior</h3><p>Session replay tools ‘record’ applications by listening for changes in the DOM (<a href="http://blog.sessionstack.com/2017/06/how-to-track-changes-in-the-dom-using-mutation-observer/">see how we do it at SessionStack by using MutationObserver</a>) as well as for all user events like mouse clicks, mouse moves, page scrolls, window resizing and so on. All static resources referenced from the page that’s been recorded need to be accessed by the 3rd party tool so that it’s able to offer a pixel-perfect replay of the session. The collected data is used by the tool to recreate every single user activity on the page in the form of a video recording.</p><p>As you can tell, a common trait across the above development platforms and frameworks is the way static resources such as imagery, fonts, multimedia, etc. get served in a closed environment, where there’s an intermediary between the browser and the application, be it a WebView or a Manifest file. In essence, all static files are embedded in the application and loaded as files that live on a local server which makes it impossible for 3rd party tools to access them from outside the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPRd7HUAlPTBhLHpdVn95A.png" /><figcaption><em>This is what you’d be hoping to see on user session replay.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-JS712RfEK9vvXRIpY18A.png" /><figcaption><em>That’s how a session replay would look like if static files have not been loaded (and recorded).</em></figcaption></figure><p>And that’s precisely why most session replay tools hit a wall trying to record and replay user activities on mobile hybrid and desktop applications, or capture browser extension usage.</p><h3>A workaround</h3><p>A solution for this problem would be to serve the resources referenced from the app on a remote server which can be accessed externally. Also, the session recording tool should provide a way to change the original resource addresses to point to the remotely accessible server.</p><p>For example, the recording tool might have the ability to map the original URLs to different ones based on some rules defined by the user.</p><p>Another option would be if the tool allows changing the server origin of the app. This method would also require that all of the URLs in the app are relative and the resources on the remote server keep the same structure as in the app. The latter method is the one we employ to make sure <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=closed-environment-post">SessionStack</a> is able to record and replay user sessions in hybrid mobile and desktop apps, as well as browser add-ins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYMgX7rTaK9euQdCzJmw2g.png" /><figcaption><em>Specify a new location for your app’s static resources to allow SessionStack to reproduce user behavior in your hybrid mobile and desktop apps.</em></figcaption></figure><p><strong>tl;dr: </strong>if you’re looking for a session replay tool to track user behavior in hybrid mobile and desktop apps, as well as browser plugins, make sure it offers a way to reach the static resource files of the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d164d1c17a67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/recording-user-sessions-in-closed-environments-hybrid-mobile-and-desktop-apps-and-browser-d164d1c17a67">Recording user sessions in closed environments: hybrid mobile and desktop apps, and browser…</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>