Guest User

Untitled

a guest
Dec 17th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. ### Instrumenting a Polymer 1.x App with User Timing API
  2.  
  3. The User Timing API let's us visualize custom timing intervals using the dev tools that are built into your web browser. While this is useful for a lot of different cases, one fun trick is to use this API to visualize the cost of the custom elements in your Polymer app.
  4.  
  5. Polymer has a few key methods whose invokations tend to represent the majority of time spent creating and initializing Polymer custom elements. Let's collect the methods we want to measure in an array:
  6.  
  7. ```javascript
  8. var instrumentedMethods = [
  9. // Standard custom element lifecycle callbacks:
  10. 'attachedCallback',
  11. 'detachedCallback',
  12. 'createdCallback',
  13.  
  14. // Interesting Polymer-specific methods:
  15. '_ready',
  16. '_registerFeatures',
  17. '_finishRegisterFeatures',
  18. '_prepBehavior',
  19. '_initFeatures',
  20. '_marshalBehavior',
  21. '_stampTemplate',
  22. ];
  23. ```
  24.  
  25. We know the methods we want to measure, now we need a way to hygeinically instrument an arbitrary method. Let's craft a helper to do this:
  26.  
  27. ```javascript
  28. function instrument(name, fn) {
  29. var count = 0;
  30. return function() {
  31. var start = this.is + '-' + name + '-start-' + count;
  32. var end = this.is + '-' + name + '-end-' + count;
  33. ++count;
  34. performance.mark(start);
  35. var result = fn.apply(this, arguments);
  36. performance.mark(end);
  37. performance.measure(this.is + '::' + name, start, end);
  38. }
  39. }
  40. ```
  41.  
  42. We now have the two most important ingredients. Next, let's make a Polymer feature by applying instrumentation to the relevant `Polymer.Base` methods and mix it in to Polymer's base implementation for all custom elements:
  43.  
  44. ```javascript
  45. var UserTiming = instrumentedMethods.reduce(function(proto, method) {
  46. proto[method] = instrument(method, Polymer.Base[method]);
  47. return proto;
  48. }, {});
  49.  
  50. Polymer.Base._addFeature(UserTiming);
  51. ```
  52.  
  53. We now have the code necessary to instrument Polymer, but it's important to make sure that the instrumentation happens at the right time. Put the instrumentation code in an HTML Import and add it to the end of `polymer.html` (right after the import for `dom-bind.html`:
  54.  
  55. ```html
  56. <link rel="import" href="src/lib/experimental/user-timing.html">
  57. ```
Add Comment
Please, Sign In to add comment