Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
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.

379 lines
13 KiB

  1. It is a well-known fact that a fast website is critical towards having high user
  2. retention. Google looks favorable upon websites which are well optimized and
  3. fast. If you are using a CMS like WordPress or Wix, a lot of optimization is
  4. done automatically. If you like to build stuff from scratch like me, there is a
  5. ton of work required to optimize a website. This post will cover the 8 things that
  6. I did to decrease the load time of this blog written in node by two seconds.
  7. # Final Results
  8. ![Final Website Speed Test](media/websiteOptimization/finalResults.png)
  9. This is the result for a single blog post.
  10. Before the improvements, my home page took 3.14 seconds to load and was 3mb. Now
  11. my home page takes 1.22 seconds to load and is only 1.2mb in size. If you look at the
  12. waterfall for my home page, most of the time is a result of the youtube embedded
  13. videos loading.
  14. # Optimize Images
  15. Since images are the largest portion of a website's size, optimizing and
  16. reducing the size of images will decrease load time. In a perfect web
  17. development world, everyone would use SVG images which are extremely small and
  18. don't need compression. I wrote a script to automatically optimize JPEG and PNG
  19. images for websites since most people don’t use SVG images.
  20. ```bash
  21. #!/bin/bash
  22. # Simple script for optimizing all images for a website
  23. #
  24. # @author Jeffery Russell 7-19-18
  25. WIDTH="690>" # the ">" tag specifies that images will not get scaled up
  26. folders=("./entries" "./img")
  27. for folder in "${folders[@]}"; do
  28. for f in $(find $folder -name '*.jpg' -or -name '*.JPG'); do
  29. convert "$f" -resize $WIDTH "$f"
  30. jpegoptim --max=80 --strip-all --preserve --totals --all-progressive "$f"
  31. done
  32. for f in $(find $folder -name '*.png' -or -name '*.PNG'); do
  33. convert "$f" -resize $WIDTH "$f"
  34. optipng -o7 -preserve "$f"
  35. done
  36. done
  37. ```
  38. This script will go through the ‘img', and ‘entries’ folders recursively
  39. and optimize all the images in there. If an image is more than 690px wide, it
  40. will get scaled down. In most cases it is useless to have images with
  41. a width greater than 690px because it will just get scaled by the client's web
  42. browser.
  43. If you are running a Debian based linux distro, you can download the
  44. dependencies for this script with the following commands:
  45. ```bash
  46. apt-get install jpegoptim
  47. apt-get install optipng
  48. apt-get install convert
  49. ```
  50. The goal of this script is to make most of the images under 100kb for the web.
  51. It is ok to have a few images above 100kb; however, you should really avoid
  52. having images above 200kb.
  53. # Take advantage of Async calls
  54. One of the largest benefits of Node is its Async abilities: code is
  55. executed in a multi-threaded fashion. This can become a "callback hell" if not
  56. handled correctly, but, with good code structure it can become very useful and easy to manage. When
  57. code is executed in parallel, you can decrease run time by doing other stuff
  58. while waiting on costly file IO and database calls.
  59. The problem with Async code is that it is hard to coordinate. Node has a lot of
  60. ways to handel synchronization; I prefer to use
  61. [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  62. Here is a simple example where Async code can be misused.
  63. Bad Async Code:
  64. ```javascript
  65. includes.printHeader(res).then(function()
  66. {
  67. return require(file).main(res, filename, request);
  68. }).then(function()
  69. {
  70. return includes.printFooter(res);
  71. }).catch(function(err)
  72. {
  73. console.log(err);
  74. })
  75. ```
  76. Good Code Async:
  77. ```javascript
  78. Promise.all([includes.printHeader(),
  79. require(file).main(filename, request),
  80. includes.printFooter()]).then(function(content)
  81. {
  82. res.write(content.join(''));
  83. res.end();
  84. }).catch(function(err)
  85. {
  86. console.log(err);
  87. });
  88. ```
  89. In the second example, three blocks of Async code are executed in parallel and in
  90. the first example three blocks of async code are executed one after another.
  91. Many people may initially do the first option because it may seem like you must
  92. create and render the footer after you render the header and body of the page.
  93. A great way to handel async calls is by having most of your methods returning
  94. promises which resolve to the HTML or DB information that they produce. When you
  95. run Promise.all, it returns an array of the results of the promises which enables you to
  96. preserve the order ie header, body, footer. After you do this for all your code,
  97. it creates a async tree which runs very fast.
  98. Another Good Async Example:
  99. ```javascript
  100. /**
  101. * Calls blog and sidebar modules to render blog contents in order
  102. *
  103. * @param requestURL
  104. * @returns {Promise|*}
  105. */
  106. main: function(requestURL)
  107. {
  108. return new Promise(function(resolve, reject)
  109. {
  110. Promise.all([renderPost(requestURL),
  111. require("../sidebar/sidebar.js").main()]).then(function(content)
  112. {
  113. resolve(content.join(''));
  114. }).catch(function(error)
  115. {
  116. reject(error);
  117. })
  118. });
  119. }
  120. ```
  121. # Client-Side Caching
  122. Client-side caching is where the client's web browser stores static content they
  123. download from your website. For example, if a client caches a CSS style sheet,
  124. they won't have to download it again for the next page they visit.
  125. You should cache all images, JavaScript and CSS files since those typically
  126. don't change. It is a good idea to set the expiration date of the cache to be
  127. something longer than a week, I typically set mine for a month.
  128. For a web browser to accept and cache files, you must set some tags in the HTTP
  129. header. In the HTTP header you must specify the content type and cache variables
  130. like max age. You also must assign a ETag to the header to give the client a way
  131. to verify the content of the cache. This enables the client to detect if there
  132. was a change to the file and that they should download it again. Some people set the ETag equal
  133. to the version of the stylesheet or JavaScript, but, it is far easier to just
  134. set it equal to the hash of the file. I use md5 to hash the files since it is
  135. fast and I'm not worried about hash collisions for this application.
  136. You can do this in NGINX if you use it to serve static files, but, you can also
  137. do it directly in Node.
  138. ## Caching CSS
  139. ```javascript
  140. var eTag = crypto.createHash('md5').update(content).digest('hex');
  141. result.writeHead(200, {'Content-Type': 'text/css', 'Cache-Control':
  142. 'public, max-age=2678400', 'ETag': '"' + eTag + '"',
  143. 'Vary': 'Accept-Encoding'});
  144. result.write(content);
  145. result.end();
  146. ```
  147. ## Caching Images
  148. ```javascript
  149. var eTag = crypto.createHash('md5').update(content).digest('hex');
  150. result.writeHead(200, {'Content-Type': 'image/png',
  151. 'Cache-Control': 'public, max-age=2678400',
  152. 'ETag': '"' + eTag + '"'});
  153. result.write(content);
  154. result.end();
  155. ```
  156. # Server-Side Caching
  157. Even with the best async server, there are still ways to improve performance. If
  158. you cache all the static pages that you generate in a HashMap, you can quickly
  159. access it for the next web user without ever having to query the database or
  160. do file IO.
  161. ## Ex:
  162. ```javascript
  163. const cache = require('memory-cache');
  164. var html = cache.get(filename);
  165. if(html == null)
  166. {
  167. // Generate page contents
  168. Promise.all([includes.printHeader(),
  169. require(file).main(filename, request),
  170. includes.printFooter()]).then(function(content)
  171. {
  172. res.write(content.join(''));
  173. res.end();
  174. cache.put(filename, content.join(''));
  175. })
  176. }
  177. else
  178. {
  179. res.write(html);
  180. res.end();
  181. }
  182. ```
  183. I found that it is the fastest to cache everything from static html pages, CSS,
  184. JavaScript, and images. For a larger site this may consume a boat load of ram,
  185. but, storing images in a HashMap reduces load time since you don't need to read
  186. the image file from the disk. For my blog, server-side caching nearly cut my load time
  187. in half.
  188. Make sure that you don't accidentally cache a dynamic page like the CMS page in
  189. your admin section — really hard to realize while debugging.
  190. To demonstrate the performance increase of this method, I restarted my web
  191. server (clearing the cache) and ran a speed test which ran three trials. The
  192. first two trials were slow since the server did not have anything in its cache.
  193. However, the third trial ran extremely fast since all the contents were in the
  194. server's cache.
  195. ![Server Cache Example](media/websiteOptimization/serverCache.png)
  196. # Enable Compression
  197. Compressing content before it is transferred over the internet can significantly
  198. decrease the loading time of your website. The only trade off from this approach
  199. is that it takes more CPU resources, however, it is well worth it for the
  200. performance gains. Using Gzip on CSS and HTML can reduce the size by 60-70%.
  201. If you are running an NGINX server, you can enable Gzip there. There is also a
  202. simple node module which will use Gzip compression on an Express app.
  203. ## Gzip on Express App
  204. ```bash
  205. npm install compression
  206. ```
  207. ```javascript
  208. var compression = require('compression')
  209. app.use(compression());
  210. ```
  211. # Remove Unused CSS Definitions
  212. If you use a CSS library like Bootstrap or W3-CSS, you will have a ton of css
  213. classes which go unused. The standard BootStrap CSS file is around 210kb. After
  214. I removed unused CSS definitions the size of the BootStrap file was only 16kb
  215. for my website.
  216. For my blog I used the node dependency PurgeCSS to remove unused CSS.
  217. This command will install PurgeCSS for CLI (command line interface).
  218. ```bash
  219. npm i -g purgecss
  220. ```
  221. This is an example of how you could use PurgeCSS to remove unused css
  222. definitions.
  223. ```bash
  224. purgecss --css css/app.css --content src/index.html --out build/css/
  225. ```
  226. PurgeCSS CLI options.
  227. ```bash
  228. purgecss --css <css> --content <content> [option]
  229. Options:
  230. --con, --content glob of content files [array]
  231. -c, --config configuration file [string]
  232. -o, --out Filepath directory to write purified css files to [string]
  233. -w, --whitelist List of classes that should not be removed
  234. [array] [default: []]
  235. -h, --help Show help [boolean]
  236. -v, --version Show version number [boolean]
  237. ```
  238. This is not the ideal solution since some CSS definitions may be used on some
  239. pages yet unused on other pages. When running this command be sure to select a
  240. page which uses all your CSS to prevent losing some CSS styling on certain
  241. pages.
  242. You don't have to use this through the command line, you can run this directly
  243. in your node app to make it automated. Check out their
  244. [documentation](https://www.purgecss.com/) to learn more.
  245. # Minify CSS and Javascript
  246. This is the easiest thing you can do to reduce the size of your website. You
  247. just run your CSS and JavaScript through a program which strips out all
  248. unnecessary characters.
  249. Ex of Minified CSS:
  250. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  251. .bg-primary{background-color:#3B536B!important}#mainNav{font-family:Montserrat,'Helvetica Neue',Helvetica,Arial,sans-serif;font-weight:700;text-transform:uppercase;padding-top:15px;padding-bottom:15px}#mainNav .navbar-nav{letter-spacing:1px}#mainNav .navbar-nav li.nav-item a.nav-link{color:#fff}#mainNav .navbar-nav li.nav-item a.nav-link:hover{color:#D2C0FF;outline:0}#mainNav .navbar-toggler{font-size:14px;padding:11px;text-transform:uppercase;color:#fff;border-color:#fff}.navbar-toggler{padding:.25rem .75rem;font-size:1.09375rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.table .thead-dark{color:#fff;background-color:#513E7D;border-color:#32383e}footer{color:#fff}footer h3{margin-bottom:30px}footer .footer-above{padding-top:50px;background-color:#3B536B}footer .footer-col{margin-bottom:50px}footer .footer-below{padding:25px 0;background-color:#3B536B}
  252. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  253. There are Node libraries which can minify CSS and Javascript, however, if you
  254. are lazy, just use a website like [this](https://cssminifier.com/).
  255. # Keep Minimal JavaScript
  256. Ignoring the gross amount of Node dependencies you have, it is critical to
  257. minimize the amount of dependencies the client needs. I completely removed
  258. BootStrap's JavaScript and jQuery from my blog by simply writing a javascript
  259. function for my nav bar. This reduced the size of my website by 100kb.
  260. ```javascript
  261. const e = document.querySelector(".navbar-toggler");
  262. const t = document.querySelector(".navbar-collapse");
  263. e.onclick = function()
  264. {
  265. if (e.getAttribute("aria-expanded") == "false")
  266. {
  267. t.classList.remove('collapse');
  268. e.setAttribute('aria-expanded', true);
  269. }
  270. else
  271. {
  272. e.setAttribute("aria-expanded", false);
  273. t.classList.add('collapse');
  274. }
  275. }
  276. ```
  277. You should debate how much you need 3rd party scripts like Google Analytics. In
  278. most cases people don't full take advantage of Google Analytics, a simple
  279. backend analytics service would work just as good while saving the client load
  280. time.
  281. # Resources
  282. - [Pingdom Speed Test](https://tools.pingdom.com/)
  283. - [Google Website Speed
  284. Test](https://developers.google.com/speed/pagespeed/insights/)
  285. - [Code to My "Optimized" Node Blog](https://github.com/jrtechs/NodeJSBlog)
  286. - [Purge CSS](https://www.purgecss.com/)
  287. - [CSS and JavaScript Minifier](https://www.minifier.org/)