Sådan opsættes ydeevne og brugersporing i React med Google Analytics

At holde styr på dine brugere og din app-ydeevne er en meget vigtig del af moderne webudvikling. Du har måske set rapporter om virksomheder, der øger indtægterne ved blot at reducere indlæsningstiden for deres app med et par hundrede millisekunder.

At holde styr på din brugeradfærd er også afgørende. Dette giver dig mulighed for at ændre og opbygge din app i henhold til dine brugeres foretrukne måde at interagere med din app på, hvilket resulterer i lykkeligere brugere og mere trafik til dit websted.  

Her er det afsluttede projekt:

//github.com/iqbal125/react-hooks-google-analytics

I denne vejledning giver jeg dig en komplet grundlæggende guide til sporing af både ydeevne og brugeradfærd. Ved afslutningen af ​​vejledningen har du alt hvad du behøver for at opbygge komplekse bruger- og præstationssporingsopsætninger.

Følg mig på Twitter for flere tutorials i fremtiden: //twitter.com/iqbal125sf

Indholdsfortegnelse

  1. Introduktion
  2. Google Analytics
  3. Sporing af sidevisninger
  4. Tracking Load Performance
  5. Sporing af gengivelsesydelse
  6. Sporing af maling
  7. Sporingsrulle
  8. Sporing af begivenheder
  9. Hurtige ydeevne tip og heuristik

Introduktion

Jeg vil vise dig præstationsmålene for udviklingen af ​​reagerer for at holde denne tutorial kortfattet. Men i en reel verdenssituation skal du ikke teste dev-versionen, fordi den indeholder en masse fejlhåndteringskode og mangel på optimeringer, der giver dig meget skæve resultater.

Af denne grund er det bedre at teste på buildproduktionsversionen for at etablere nogle baseline-metrics.

For kortfattethed vil jeg også henvise til Google Analytics som GA.

GA fungerer heller ikke med lokal vært. For at få en simulering af, hvad du muligvis sender til GA uden faktisk at sende det og ødelægge din analyse, kan du bare erstatte en console.log, uanset hvor du planlægger at sætte dit GA-hit.

ReactGA  er den globale funktion og er kendt som kommandokøen, fordi den ikke udfører kommandoer med det samme, men føjer kommandoer til en kø og sender dem derefter asynkront. Dette binder ikke hovedtråden og fører ikke til, at din sporingskode skader din apps ydeevne.

Et hit er, når en GA-tracker sender data til Google Analytics.

Vi fokuserer primært på React-koden i denne tutorial, der er langt bedre andre tutorials til at lære at bruge GA.  

Der er 3 hovedfunktioner, vi vil bruge, når vi sender hits til GA. Du bør vide, at der er flere, men vi vil bare fokusere på disse 3 i forbindelse med denne vejledning.

GAReact.pageview(): vil passere i en streng, der indeholder ruten.

GAReact.timing(): Tager et objekt som parameter. Indeholder oplysninger relateret til vores præstationsmålinger, som vi vil se nedenfor. Felterne vil være category, variable, valueog label. Bemærk, at kun værdiegenskaben kommer fra vores app, resten af ​​egenskaberne er brugerdefineret.

GAReact.event(): Tager et objekt som parameter. Vil indeholde data om begivenheder, der finder sted i app (formular indsende, knap klik, etc.) Vil have områder category, action, labelog value. Bemærk, at kun værdien kommer fra appen, resten af ​​egenskaberne er brugerdefineret.

Syntetisk test vs RUM

Du undrer dig måske over, hvorfor gå igennem alle disse problemer med at opsætte Performance Observer-metrics, hvis du bare kan bruge et værktøj som Lighthouse eller en webside-hastighedstest og få disse metrics ved bare at indtaste url.

Værktøjer som disse er vigtige, men de er det, der er kendt som syntetisk test, da testen udføres på din enhed, og testen afspejler faktisk ikke, hvad dine brugere oplever. Du kan reducere CPU'en eller netværket, når du foretager disse tests, men de er stadig simuleringer.

Brug af GA med Performance Observer-metrics giver os reelle tal fra vores faktiske slutbrugere, enheder og netværk. Dette er kendt som RUM eller Real User Monitoring.

Syntetiske testværktøjer. Indtast blot URL'en til din app for at køre de syntetiske tests.

  • //www.webpagetest.org/
  • //www.thinkwithgoogle.com/feature/testmysite
  • //developers.google.com/speed/pagespeed/insights/
  • //www.uptrends.com/tools/website-speed-test
  • //tools.pingdom.com/

Google Analytics

Opsætning

Hvis du allerede har Google Analytics-opsætning på din app, er du velkommen til at springe dette afsnit over, der er ikke noget nyt her.

For at konfigurere GA skal du gå til instrumentbrættet og klikke på fanen admin i sideskuffen. Klik derefter på tilføj ejendom. Udfyld den nødvendige info.

Hvis du læser denne vejledning, antager jeg, at du er smart nok til at konfigurere Google Analytics med netop disse 3 instruktioner. Hvis ikke, her er en praktisk guide fra Google.

//support.google.com/analytics/answer/1042508?hl=da

Når du er færdig med opsætningen, får du et sporings-id øverst, som vi bruger i vores React-app.

Opsætning i reaktion

Vi behøver ikke at genopfinde hjulet her, vi kan bruge et hjælperbibliotek lavet af Mozilla Foundation til at hjælpe os med React-opsætningen.

For at installere biblioteket skal du blot køre

npm install react-ga

Derefter skal du bare importere ReactGA-objektet, hvor som helst du vil bruge det

import ReactGA from 'react-ga';

Du skal også initialisere den i rodkomponenten med sporings-id'et fra Google Analytics.  

... ReactGA.initialize('UA-00000-1'); ...

Observatører

ReactGA cant do anything besides send data to the Google Analytics website. To actually get performance metrics to send, we will use the Performance Observer browser API. This Performance Observer API has nothing to do with GA or even React, it is a browser API that is available in most modern browsers

How the PerformanceObserver and related APIs work exactly is a fairly big topic and is far out of the scope of this tutorial. See the Further Reading section for more info and links to tutorials.

The basic idea of how they work is they "observe" something and then send that data asynchronously at the time of the browsers choosing. This keeps the main thread free for critical app functionality and related tasks, therefore tracking events does not affect your app performance.

Before observers you would have to add an event listener and fire it synchronously every time something happened, this resulted  in noticeable performance issues if too many events were being fired at once. So this is the problem observers are looking to solve.

Track Page Views

Tracking page views in a single page app like react may seem like it would be complicated but its relatively simple thanks to react-router and history libraries.

history.listen((location) => { ReactGA.set({ page: location.pathname }); ReactGA.pageview(location.pathname) } );

history.listen() allows you to fire a callback on route changes which in our case happens to be the GA hit. The route is contained in the pathname property of location.  But there are a couple of things to note such as:

Handling the intial load

History is listening for page changes but it doesn’t cause a hit on the initial page load.

There are a few ways to handle the initial load. I found a simple way to do it that I think requires the least amount of code and complexity and it is just to have an initial load variable and save it to the global state. In the home page just use a conditional to check if it is false then set it to true after the hit.

Context variable in the parent component

... const [initialLoad, setInitialLoad] = useState(false) ...  setInitialLoad(true), >

Then the useEffect() in the home child component

... useEffect(() => { if(!context.initialLoadProp) { ReactGA.pageview(props.location.pathname); context.setInitialLoadProp(true) } }, []) ... 

There are other implementations and discussions you can find here:

//github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker

Tracking pages with User ids

Another thing you might want to know is how many users are visiting their private profile pages. Just using the pageviews would give you a unique url for every hit and will not work.

Say you have the following URLs with user ids:

user/4543456/messages

user/4543456/account

user/3543564/messages

user/3543564/replytomessage

user/3543564/account

These will all give you a unique page hit. A simple fix is to just check with a conditional and then remove the unique id. You can also use a conditional to make sure you dont send these pages to google analytics.

... history.listen((location) => { if(location.pathname.includes('/user')) { let rootURL = location.pathname.split('/')[1] let userPage = location.pathname.split('/')[3] let pageHit = `/${rootURL}/${userPage}` ReactGA.pageview(pageHit) } else { ReactGA.set({ page: location.pathname }); ReactGA.pageview(location.pathname) } }); ...

We are simply just parsing out the user id and then concatenating the route again before sending the hit.

This would probably not be true for forum posts since having a unique URL for each post would be correct, since you would like to know how many people visited each post.

Tracking Load Performance

Getting the load performance is relatively easy. All the load performance data is under the navigation entry which is part of the navigation timing API.

The Performance Observer Can be setup like so in the root parent component.

const callback = list => { list.getEntries().forEach(entry => { ReactGA.timing({ category: "Load Performace", variable: "Some metric", value: "Value of Metric" }) }) } var observer = new PerformanceObserver(callback); observer.observe({entryTypes: ['navigation'] })

First we define a function to be called for each entry. Then we pass this callback into our PerformanceObserver and finally we call the .observe() method on our observer and pass in navigation as an entryType.  

This will give you the following entry:

This is a very large amount of information but really we need only 3 properties to track the main load performance:

requestStart: when the browser issues a request to get the webpage from the server

responsesStart: when the first byte of the website arrives

responseEnd: When the last byte of the website arrives

There are a few things that happen before the requestStart such as DNS lookup and the TLS handshake. Use this data and see if you can combine it with other properties to make new metrics.

With the above three properties we can create 3 important metrics. Simply substitute in the variable and value properties for the respective metric.

const callback = list => { list.getEntries().forEach(entry => { ReactGA.timing({ category: "Load Performace", variable: 'Server Latency', value: entry.responseStart - entry.requestStart }) }) }

Server latency:

entry.responseStart - entry.requestStart

Download time:

entry.responseEnd - entry.responseStart

Total app load time:

entry.responseEnd - entry.requestStart

Time to Interactive

This metric is essentially how long it takes for a user to be able to interact with your site.

Until a native TTI metric is available through the browser api we can use this handy polyfill npm module for now. This module is created by Google.

npm install tti-polyfill

Then we can use the polyfill like so.

... import ttiPolyfill from 'tti-polyfill'; ttiPolyfill.getFirstConsistentlyInteractive().then((tti) => { ReactGA.timing({ category: "Load Performace", variable: 'Time to Interactive', value: tti }) }); ...

We are simply sending a hit inside of our function with a chained .then() statement since we will retrieve this metric asynchronously.

Tracking Rendering Performance

Now we can discuss Rendering Performance, which is how long it takes for React to construct the tree of DOM nodes. We can track rendering performance with the mark and measure entries.

mark is used to "mark" a point in time you want to keep track of. Just pass in a string as the name of the mark on the exact line you want mark for tracking.

performance.mark("name of mark")

measure is the difference between the 2 marks. Just set the name of the measure and pass in start and end marks, which will give you the difference between the marks in milliseconds.

performance.measure.("name of mark", startingMark, EndingMark)

Thankfully React comes pre-bundled with these marks and measures, which saves us from having to open up the React Source and having to write them ourselves. Simply pass in mark and measure for the entry types and you're done.

... var observer = new PerformanceObserver(callback); observer.observe({entryTypes: ['mark', 'measure'] }) ...

This will give you the time it takes for root parent component and all child components to render in milliseconds. You will get entries that look something like this:

You will also get the time it takes for the lifecycle methods to execute. There is a wealth of information here, simply pick what you want to track and send it to GA by checking for the name in a conditional statement.

... const callback = list => { list.getEntries().forEach(entry => { if(entry.name.includes('App') ) { ReactGA.timing({ category: "App Render Performace", variable: entry.name, value: entry.duration }) } }) } ...

Tracking Paint Performance

Now we can track paint which is when the pixels are drawn (or "painted") to the screen after the DOM tree is rendered.  

Tracking paint performance comprises 3 metrics: First Paint, First Contentful Paint and First Meaningful paint.

First Paint: First time anything besides a blank white page is present.

First Contentful Paint: When the first DOM element is present. Text, image etc.

First Paint and First Contentful Paint will be given automatically by the API. Simply do the following:

... const callback = list => { list.getEntries().forEach(entry => { ReactGA.timing({ category: "Paint", variable: entry.name, value: entry.startTime }) }) } var observer = new PerformanceObserver(callback); observer.observe({entryTypes: ['paint'] })

The entries will look like this

It is entirely possible that both these metrics are exactly the same, down to the millisecond. Even if they are not the same there can be an irrelevant difference between them. For this reason another more flexible metric is used, called:

First Meaningful Paint: When something “meaningful” is painted to the screen. “meaningful” is kept intentionally vague, allowing the developer to decide themselves what they want to test for.  

According to Google, the First Paint and First Contentful paint answer the question of “Is it happening” and First Meaningful Paint answers “Is it useful”. “Is it useable” is answered by Time to Interactive.

A common way to use First Meaningful paint is to test for the hero element. Which is the main element on the page.

An example for youtube would be the video player. Suggested videos and comments would all then be non hero secondary elements. Tracking when the video player has finished painting would be the First Meaningful Paint in this case.

A common hero element on the homepage is a background image near the header that gives the value proposition or theme of the website. Knowing this, we can use the resource timing api to measure when our image has finished loading and make this our First Meaningful paint metric.

If your hero element is an image then you can simply look at the resource timing API and then look at responseEnd property and use that as your FMP.

... const callback = list => { list.getEntries().forEach(entry => { ReactGA.timing({ category: "First Meaningful Paint", variable: entry.name, value: entry.responseEnd }) }) } var observer = new PerformanceObserver(callback); observer.observe({entryTypes: ['resource'] }) ...

Entire resource timing response.

Since the loaded image doesn't technically mean its painted you can also try to set the marks manually.

 //jsx {performance.mark('start')  {performance.mark('end') {performance.measure('diff', 'start', 'end') 

Again there is a lot of flexibility in this metric, really consider your use case and what your trying to measure.

Track Scroll

Tracking the scroll position of your user is a fairly important part of analytics. You can for example see how many users scrolled past a certain image or section of text. Having this information you can then tweak your content and increase your conversion.

You would have seen older implementations use getBoundingClientRect() but this would tie up the main thread and therefore tracking the scroll would actually decrease performance. You can execute the scroll events asynchronously with IntersectionObserver.  

The IntersectionObserver is different than the PerformanceObserver we have been working with in the last sections.

The IntersectionObserver takes 2 arguments a callback and a options object. The options object will have 3 properties

root: The element you are trying to test the intersection against. In most cases this will be the viewport which will be the value of null.

rootMargin: The margins around the root element. ex: "10px"

threshold: How much of the element is visible before isIntersecting is true. ex: 0.5 means isIntersecting  is true when 50% of the element is visible. 0 means the very top of the element and 1.0 means the entire element.

The entry will return an object like so:

isIntersecting:  Essentially used to determine if the element is visible which would be true when the threshold is reached.

And now the code:

//Get the element you want to track with useRef const intersectTarget = useRef(null) //Use the observer inside the component you want to track scroll useEffect(() => { const opts = { root: null, rootMargin: '0px', threshold: 0 } const callback = list => { list.forEach(entry => { if(entry.isIntersecting) { ReactGA.event({ category: 'Scroll', action: 'Scrolled to heading 2', value: entry.intersectionRatio }) } }) } const observerScroll = new IntersectionObserver(callback, opts) observerScroll.observe(intersectTarget.current) }, []) //jsx 

Second Heading

The main idea here is to first initialize the useRef hook. Then use the ref on the element you want to track for scroll. The callback and observer will be called in the useEffect hook and the element can be passed to the .observe() method with the name of the ref and the .current property.

Note: The intersection observer will fire on the initial page load even if the element is not visible. This is normal and you will see that the isIntersecting property is false.

Note also: At the time of this writing there is also an isVisible property on the entry, but it does not function as its name suggests. It stays false even when the element visible. It is not documented anywhere so I cant comment on its purpose, but I would suggest using isIntersecting   property instead.  

Track Events

The basic idea to tracking events is to send GA hits inside of the function call attached to an event handler. There really isn’t much more to it than that.

One thing to note is if your user is submitting a form you can specify the     transport: beacon property in your event hit, which will let you reliably send the hit even if the page is reloaded to another page. This isn't so much of an issue in a single page app like React, but if you did want to do this, just know this option is available.

See the navigator beacon for more info

I will show you how to track a form submit, but this pattern will work with basically any event. Again you are simply sending the hit in a function attached to the event handler.

 ... const handleSubmit = (event) => { event.preventDefault(); ReactGA.event({ category: 'Form', action: 'Form Submit', transport: 'beacon' }); apiCall('/apicall', event.target.value) }; ...  ...  ...

Quick Performance Tips and Heuristics

Biggest area for improvement I see for a lot of developers is to code things from scratch instead of using a library. Tree shaking reduces bloat a little bit, but there is still considerable bloat compared to coding something yourself. Which will allow you to only write the code you need.  Try to use as little libraries as possible. Instead of using a library for a few functions, try to just look at the source code of the library and try to implement those functions yourself. Also keep in mind that most libraries have to prioritize ease of use and personalization over performance.

Some other ones:

  • For event firing like scroll you will definitely need debouncing/throttling. You don't need to do this for observers.  
  • Only import functions and variables you need and let tree shaking discard unused code.
  • Do not pass in an anonymous function to events.
  • Turn your React app into a PWA allowing users to download and install your webapp locally on their device.
  • Reduce payloads with code splitting and lazy loading.
  • Decrease file size by using gzip or similar compression
  • Serve images from a CDN
  • Enable caching through your http headers on server responses.
  • Optimize images. See the google fundamentals guide for a full guide on how to do so.
  • Use the new CSS Flexbox for layout. Avoid Layout Thrashing
  • Only Use transforms and opacity for css changes. So instead of changing height and width use scale X and scaleY

Luckily, A lot of these optimizations, like minification and gzip, are done for automatically when you run the npm build command on a React Project.

Conclusion

Tak for læsningen! Hvis du fandt andre kreative målinger eller kloge måder at spore brugere på, så lad mig det vide i kommentarerne.

Følg mig på twitter for flere tutorials i fremtiden: //twitter.com/iqbal125sf

Blogindlæg:

//www.searchenginejournal.com/a-technical-seo-guide-to-lighthouse-performance-metrics/292703/#close

//infrequently.org/2017/10/can-you-afford-it-real-world-web-performance-budgets/

//speedcurve.com/blog/user-timing-and-custom-metrics/

//designsystem.digital.gov/performance/

//hackernoon.com/react-performance-primer-64fe623c4821

//reactjs.org/docs/optimizing-performance.html

Observatører:

//css-tricks.com/paint-timing-api/

//css-tricks.com/breaking-performance-api/

//hackernoon.com/tracking-element-visibility-with-react-and-the-intersection-observer-api-7dfaf3a47218

//www.smashingmagazine.com/2018/01/deferring-lazy-loading-intersection-observer-api/

//www.sitepen.com/blog/improving-performance-with-the-paint-timing-api/

Google-baseret:

//developers.google.com/web/fundamentals/performance/user-centric-performance-metrics

//developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/

//developers.google.com/web/tools/chrome-devtools/speed/get-started

//marketingplatform.google.com/about/optimize/

//developers.google.com/analytics/devguides/collection/analyticsjs/user-timings

//support.google.com/analytics/answer/1033068#Anatomy

//developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

//support.google.com/analytics/answer/1033068

//docs.google.com/document/d/1GGiI9-7KeY3TPqS3YT271upUVimo-XiL5mwWorDUD4c/preview#

//www.doubleclickbygoogle.com/articles/mobile-speed-matters/