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