<?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 Harry Vane on Medium]]></title>
        <description><![CDATA[Stories by Harry Vane on Medium]]></description>
        <link>https://medium.com/@sleepyharry?source=rss-31737b3d2db0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*G8KuzWKDrSWWKL3AiYe_NA.png</url>
            <title>Stories by Harry Vane on Medium</title>
            <link>https://medium.com/@sleepyharry?source=rss-31737b3d2db0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:18:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sleepyharry/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[Anatomy of a Snippet]]></title>
            <link>https://medium.com/shapelabs/anatomy-of-a-snippet-fdd93558ff?source=rss-31737b3d2db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdd93558ff</guid>
            <category><![CDATA[snippet]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[example]]></category>
            <category><![CDATA[analytics-platforms]]></category>
            <category><![CDATA[breakdown]]></category>
            <dc:creator><![CDATA[Harry Vane]]></dc:creator>
            <pubDate>Thu, 17 Jan 2019 18:59:58 GMT</pubDate>
            <atom:updated>2019-01-17T18:59:58.538Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever used a service like <a href="https://analytics.google.com/analytics/web/">Google Analytics</a> or <a href="https://mixpanel.com/">Mixpanel</a>, and wondered what <em>exactly</em> it is you’re blindly copy-pasting onto your website?</p><p>This article aims to demystify and break down what a snippet actually does, and why it does it, so that next time you’re asked to copy-paste some complex-looking code onto your website, or perhaps even build a snippet for your own projects, you’ll have a better understanding about what actually makes a snippet a snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aUQhKmuFHBc4o2Nf" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>. This is not a snippet.</figcaption></figure><p>While building <a href="https://nomlyalpha.info/">nomly</a> - a service built by <a href="https://shapelabs.co/">shape</a> currently in alpha that helps you discover what visitors are searching for on your website - we decided that we wanted to make it easy for our target market (product managers and product marketing managers, primarily) to get going with nomly, and this meant making it easy to set up and install, without having to rely on anyone having technical knowledge or familiarity with particular software and tools like <a href="https://www.npmjs.com/">npm</a>. In order to do this, we looked at what other similar “analytics”-type platforms did, such as <a href="https://heapanalytics.com/">Heap</a> and Mixpanel.</p><p>It was instantly obvious that the way that these other services achieve this is through what are commonly referred to as “snippets” - small pieces of code that only require someone to copy-paste them into the HTML code of a website, that will “magically” install the service and enable analytics to start being generated.</p><p>There’s a more technical breakdown of the anatomy of a snippet towards the end of this article, but I’ll start by going through the problems snippets try to solve, and how they do so.</p><h3>Problem(s)</h3><p>There are a couple of problems that snippets in general exist to solve.</p><p><strong>For a user, they want to be able to install a service on their website, ideally without going through a long technical process.</strong> Quite often, the user / customer will be someone who isn’t “under the hood” of the codebase day-to-day, and doesn’t necessarily have either the know-how to jump through - or often even access to - the various hoops they might have to jump through in order to do a manual installation.</p><p><strong>For a service provider, they want to be able to onboard users efficiently and effectively, and be able maintain their code. </strong>The first of these relates to the user side of the problem, above, and reduces the burden on first-line support. The second factor means that if a bug is found (the horror!), then a patch can be shipped without having to get all users to download a new version of the code.</p><p>These two by themselves don’t naturally lead to snippets as a solution, however.</p><p>You would be right in saying that the above problems are both solved by having a piece of code in the source html of a web page along the lines of:</p><pre>&lt;script src=&quot;https://nomlyalpha.info/nomly.min.js?appid=xxxx&quot; /&gt;</pre><p>This is very easy to just copy and paste, and certainly solves any maintenance issues, as it simply gets the newest version of the hosted code every time.</p><p>Unfortunately, there’s a more technical - and more subtle - problem with this. Every time you load a page, the script has to be loaded from the third-party server. This takes a little time, depending on the size of the script itself. The script then has to execute all of the clever bits and pieces of code it needs in order to initialise itself and start listening to events (in nomly’s case, search queries made by site users), which again takes a not insignificant period of time. This is all time that the end-user is waiting patiently. By “waiting patiently”, I of course mean more likely than not giving up after approximately three seconds (<a href="https://think.storage.googleapis.com/docs/mobile-page-speed-new-industry-benchmarks.pdf">source</a>).</p><p>The more web developery among you will of course point out the existence of the async keyword which allows running computationally expensive scripts while the rest of the site loads, which stops the whole site waiting while the external script executes, in turn preventing user drop-off before they’ve got past the landing page. While correct, this introduces a fun new problem: <strong>Any calls to the service that happen in your code <em>before</em> the main service script is loaded and executed won’t act as expected.</strong></p><p>For example, if you’re calling a direct tracking function like nomly.log, heap.track, etc. somewhere in your code, and that happens to be before the respective functions have been created, then - at best - those tracks won’t be counted. At worst, it’ll cause a ReferenceError, and potentially crash the site.</p><h3>So what does a snippet actually <em>do?</em></h3><p>Snippets, for the most part, do three primary things. Several companies have leveraged snippets to address different needs and solve various product-specific goals, but they all have the same fundamental tasks that need doing:</p><ol><li><strong>Create a global object that will contain the main functionality of the service, as well as expose any necessary API to the web developer. </strong>This is typically achieved by declaring a property on the global window object that can then be accessed by the rest of the code on the site.</li><li><strong>Ensure that no service API calls that occur between page initialisation and full execution of the external script are missed.</strong> This is done by making “placeholder” functions that mimic the shape of the API that will be loaded, but act as a record of which calls have been made in this limbo time between the snippet running and the full service API being built by the main script, with the intention that the main script will then call these retroactively.</li><li><strong>Embed the main script.</strong> The above two steps are essentially preparation for the main event, the full script from the company’s servers being downloaded and initialised. This simply inserts the &lt;script async src=&quot;https://nomlyalpha.info/nomly.min.js?appid=xxxx&quot; /&gt; alluded to above into the body of the HTML. This script contains logic to go through the “backlog” created by calls to placeholder functions.</li></ol><p>These ensure that services are easy to install for users, and easy to maintain for service providers, while also ensuring there are no API calls missed while loading the full script in the background.</p><h3>Conclusion</h3><p>In this article we’ve seen what problems snippets aim to solve, and how in general they go about this. I hope that you’ve either got a better understanding of what it is you’re actually copy-pasting next time you use a snippet from a company’s site, or perhaps even an idea about what you need to do to build your own!</p><p>(Note: If you’re interested in a more detailed line-by-line breakdown of a snippet, you can find that below. I figure that this is a good jumping-off point if the phrase “line-by-line code” doesn’t particularly excite you.)</p><p>Next time you come across a snippet, perhaps you can break it down and decipher what it’s doing? Some have different approaches, but all do essentially the same thing.</p><p>I’d love to hear if this has helped you in any way, or if anything in this article is wrong or misleading, so do comment below, or reach out to me via email at harry@shapelabs.co</p><p>Oh, and don’t forget to get your very own <a href="https://nomlyalpha.info/">nomly snippet</a> to help you track user searches on your own site! nomly is currently in very early alpha stages of development, so any and all feedback is hugely helpful. Don’t hesitate to join our <a href="https://join.slack.com/t/nomly-alpha/shared_invite/enQtNTIxNzM2MjMwMDk5LTkzMGRkZjFiZjk2ZTVlYmFlMWNlODE3NThhMzNmYmJjY2Q1YjljNGUyYzUyNzI0OGJhNzA1YzEzMWI1YjExNjU">slack</a> and get in touch directly!</p><h3>Breakdown</h3><p>So, above we saw the role of a snippet in general, and why they’re a good solution to the problems outlined above. But how are they actually <em>constructed</em>? The rest of this article will be going into detail around the specific lines of code that achieve each task above.</p><p>While trying to understand how to go about building my own snippet, I looked at what other companies did to try to learn from them. The two I focussed on were Heap and Mixpanel, as they seemed to be providing a service most similar to what we wanted to with <a href="https://nomlyalpha.info/">nomly</a>. To begin, I needed to break apart what they had, which involved firstly “de-minifying”, whereby I essentially just pasted the snippet into my IDE and hit “auto-format”, which added in a lot of helpful whitespace, and then renaming variables to make them more understandable. Renaming was again achieved via my IDE, which understood how to rename all occurrences of a variable in scope (shoutout to <a href="https://www.jetbrains.com/pycharm/">PyCharm</a>).</p><p>So, this turned Heap’s snippet from:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14c861e4d874eba000e2dc777f26e838/href">https://medium.com/media/14c861e4d874eba000e2dc777f26e838/href</a></iframe><p>into:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/361710f567a4d726cf1d275fdb62dcaf/href">https://medium.com/media/361710f567a4d726cf1d275fdb62dcaf/href</a></iframe><p>Much more understandable! You can already pretty much see where each of the three tasks is achieved.</p><p>Mixpanel’s was very similar in structure, but had some extra tasks it needed to accomplish for Mixpanel specifically. Here is just my de-minified / renamed version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d39649a1ad48e521eb6642ebb336cd7/href">https://medium.com/media/7d39649a1ad48e521eb6642ebb336cd7/href</a></iframe><p>From here on, I’ll actually be breaking down the snippet I created for nomly. The structure is very similar to Heap’s, as there is very little “extra” to it beyond the core functionality. The equivalent of each section of code should be easily recognisable in the Heap and Mixpanel snippets above. I’ll work with the un-minified version for obvious reasons.</p><p>So, this is a rough depiction of what each block of code does, which I’ll go through in more detail below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8da058073e8ce8ac4b82307488f31c15/href">https://medium.com/media/8da058073e8ce8ac4b82307488f31c15/href</a></iframe><h4>Create global variable (without overwriting)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33c75c3ece4e8508ace8085c4760b33/href">https://medium.com/media/e33c75c3ece4e8508ace8085c4760b33/href</a></iframe><p>This is the simplest part of the snippet. It simply declares a global variable (any variable declared as a property on the window object is accessible in any javascript running on the page, even in the developer console), or uses the already declared one.</p><h4>Declare initialisation / load function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57920aee8c9d33fc04acde61679f37e2/href">https://medium.com/media/57920aee8c9d33fc04acde61679f37e2/href</a></iframe><p>This declares the main initialisation function, which we need to call with the appropriate appid to ensure we associate events with the right application server-side. We could theoretically generate the snippet with this appid already baked in, but it’s typically better practice to separate configuration from functionality. It also makes it easier for an end user to switch out the appid if they so wish, or declare it differently based on the app’s current environment - a practice we encourage!</p><h4>Add reference properties from this initialisation to the global object</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2196fb606ac796b60f606a602d87213/href">https://medium.com/media/b2196fb606ac796b60f606a602d87213/href</a></iframe><p>This gives global access to relevant properties likely to be used by the main script. Heap also allows for custom config to be placed here, for example.</p><h4>Create the &lt;script /&gt; element</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc2ee109b21e25bd598f863c5a364658/href">https://medium.com/media/bc2ee109b21e25bd598f863c5a364658/href</a></iframe><p>This is a critical component, as this part of the function creates the &lt;script /&gt; element we need to load the main script. It’s essentially writing out the full element declaration in a very manual way.</p><p>I’ll go through line-by-line, showing the result of each.</p><p>var script = document.createElement(&#39;script&#39;); does what it says, it creates a new element (not yet attached to the DOM) with the tag name “script”. After this line, script is &lt;script /&gt; .</p><p>script.type = &#39;text/javascript&#39;; helps browsers understand that the contents of this are indeed executable JavaScript. After this line, script is &lt;script type=&quot;text/javascript&quot; /&gt;.</p><p>script.async = true; ensures that the script doesn’t block the rest of the page from parsing and loading. After this line, script is &lt;script async type=&quot;text/javascript&quot; /&gt;.</p><p>script.src = ‘http’ + (ssl ? ‘s’ : ‘’) + ‘://nomlyalpha.info/nomly.min.js?appid=’ + appid; this is a URL for the script itself, customised for each individual appid by the server.</p><p>Assuming your page is served over https and your appid is xxxx, the script element built will be:&lt;script async type=&quot;text/javascript&quot; src=&quot;https://nomlyalpha.info/nomly.min.js?appid=xxxx&quot; /&gt;, which is enough to load the main script.</p><h4>Insert the newly created &lt;script /&gt; element onto the page</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7d53a34ee80a514c161595a235a5c4/href">https://medium.com/media/df7d53a34ee80a514c161595a235a5c4/href</a></iframe><p>Once we’ve built the script element, we just need to insert it into the page so that it can download and execute the main script. To do this, we look for the first script tag in the DOM (note that because the snippet itself is within a script tag, the array (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName">well, </a><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName">HTMLCollection technically</a>) is guaranteed to have at least one indexable element), and simply insert our newly built element before it.</p><p>The script will start downloading and executing as soon as it can, which is based on some complex browser rules that are a story for a later time. (sidenote: there’s a great series on Medium going in-depth on “How JavaScript works” by <a href="https://medium.com/u/e73a28627bab">Alexander Zlatkov</a> which I very much recommend. Part 1 <a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf">here</a>.)</p><h4>Create placeholder functions</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89b2da7499d2e8f2f765d128cd66e166/href">https://medium.com/media/89b2da7499d2e8f2f765d128cd66e166/href</a></iframe><p>This (at least to me!) is the most complex part of snippets. The code is a little opaque to help with reducing the size of the snippet itself, so I’ll talk through in plainer english rather than directly breaking down the code itself.</p><p>The meat of this is the makePlaceholder function. What this does is given a prop (short for “property name”), it’ll return a function that adds to a global queue an array representing the property name (for example &quot;track&quot;) as well as the arguments its called with.</p><p>So, if I do nomly.track = makePlaceholder(&quot;track&quot;), then nomly.track is now itself a function that when I call it with, say, the string &quot;potatoes&quot;, it’ll append an array [&quot;track&quot;, &quot;potatoes&quot;] onto the global nomly object.</p><p>Using this for various properties and calls will start building up what is simply a record of function calls. The main script (once it actually <em>bothers </em>to get going) will then go through this generated array, and in a sense “replay” the function calls it finds. Using the above example, when it finds [&quot;track&quot;, &quot;potatoes&quot;] it knows that it needs to call the proper track function with the single argument &quot;potatoes&quot;.</p><p>The other two sections of code simply declare the properties we’d like to make placeholders for, and then iterates over them, adding each to the global nomly object.</p><p>(Technical sidenote: the nomly “object” I refer to is actually declared as an Array, but because JavaScript is built the way it is, we can still attach properties to Arrays as if they were more explicitly declaredObjects.)</p><h4>Initialise!</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e911c085ac089b4d306b12a880e099c5/href">https://medium.com/media/e911c085ac089b4d306b12a880e099c5/href</a></iframe><p>Using your appid, run the whole function above! Everything will then be installed and start working with the main script running on your site.</p><p>That’s all there is to it! Hopefully you now have a good understanding of the structure of most snippets. Those that don’t look like the ones in this article (for example google’s “gtag” snippet) will still be doing very similar jobs, but in either a slightly different way or to achieve something specific to the related product.</p><p>As before, I’d love to hear from you if you have any feedback either about this article in particular, or <a href="https://nomlyalpha.info/">nomly</a> itself. You can get in touch in the comments below, via email (<a href="/service/mailto:harry@shapelabs.co">harry@shapelabs.co</a>), or via nomly’s dedicated <a href="https://join.slack.com/t/nomly-alpha/shared_invite/enQtNTIxNzM2MjMwMDk5LTkzMGRkZjFiZjk2ZTVlYmFlMWNlODE3NThhMzNmYmJjY2Q1YjljNGUyYzUyNzI0OGJhNzA1YzEzMWI1YjExNjU">slack channel</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdd93558ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shapelabs/anatomy-of-a-snippet-fdd93558ff">Anatomy of a Snippet</a> was originally published in <a href="https://medium.com/shapelabs">shapelabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>