You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.6 KiB

4 years ago
  1. +++
  2. title = "Fetch Injection"
  3. description = "Load external scripts and styles with incredible speed."
  4. categories = ["experience"]
  5. tags = ["performance", "styles"]
  6. features = ["snippets", "related content", "code highlighter"]
  7. [[copyright]]
  8. owner = "Josh Habdas"
  9. date = "2019"
  10. license = "agpl-3.0-or-later"
  11. +++
  12. After Dark uses the {{< external rel="external help" href="https://git.habd.as/jhabdas/fetch-inject" text="Fetch Inject" />}} library to load and execute external scripts and styles faster than browsers are capable of otherwise.
  13. {{< external href="https://hackcabin.com/post/managing-async-dependencies-javascript/" text="Fetch Injection" />}} was conceptualized and developed for After Dark to make it possible to deep-link to full-sized [Image Gallery](/module/hall-of-mirrors) images without blocking page load and has other performance applications:
  14. <table>
  15. <thead>
  16. <tr>
  17. <th rowspan="2" scope="col">Use Case</th>
  18. <th colspan="2" scope="col">Chrome Performance Comparison (4G simulated connection speed)</th>
  19. </tr>
  20. <tr>
  21. <th scope="col">Without Fetch Inject</th>
  22. <th scope="col">With Fetch Inject</th>
  23. </tr>
  24. </thead>
  25. <tbody>
  26. <td>{{< external href="https://habd.as/talks/screaming-fast-wordpress-redis-vultr/" text="WordPress Twenty Seventeen" />}}</td>
  27. <td>~3.600s</td>
  28. <td>~0.918s</td>
  29. </tbody>
  30. </table>
  31. Use Fetch Inject in your [Custom Layouts](../custom-layouts) to load scripts and styles cross-origin or from your site `static` directory.
  32. Given the following `static` folder contents:
  33. ```
  34. ├── layouts
  35. ├── static
  36. │ ├── js
  37. │ │ ├── jquery.slim.min.js
  38. │ │ ├── tether.min.js
  39. │ │ └── bootstrap.min.js
  40. │ └── css
  41. │ └── font-awesome.min.css
  42. └── themes
  43. ```
  44. You can load Bootstrap (w/Font Awesome) and show how long ago it finished:
  45. {{< highlight html "linenos=inline" >}}
  46. <script>
  47. fetchInject([
  48. 'https://cdn.jsdelivr.net/lodash/latest/lodash.min.js',
  49. 'https://cdn.jsdelivr.net/momentjs/latest/moment.min.js'
  50. ])
  51. .then(() => {
  52. const start = moment();
  53. fetchInject(['/js/bootstrap.min.js'],
  54. fetchInject([
  55. '/js/jquery.slim.min.js',
  56. '/js/tether.min.js',
  57. '/css/font-awesome.min.css'
  58. ])
  59. ).then(console.log(`Bootstrap Loaded: ${_.capitalize(start.toNow())}.`));
  60. });
  61. </script>
  62. {{< /highlight >}}
  63. Fetch Inject is 555 bytes compressed, non-blocking and included by default in [Custom Layouts](../custom-layouts). Visit the {{< external href="https://codepen.io/jhabdas/pen/MpVeOE?editors=0012" text="CodePen Playground" />}} to try it out.