lightweight-router 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Lightweight Router
2
2
 
3
- A lightweight client-side router with intelligent prefetching capabilities for modern web applications.
3
+ A minimal lightweight client-side router with intelligent prefetching capabilities for faster websites. This tool can turn any Multi-Page Application (MPA) into a Single-Page Application (SPA) very easily and with just ~1.5KB byte (gzipped).
4
4
 
5
5
  ## Features
6
6
 
@@ -8,11 +8,152 @@ A lightweight client-side router with intelligent prefetching capabilities for m
8
8
  - 🔄 Smooth client-side navigation
9
9
  - 📥 Intelligent link prefetching
10
10
  - 🎯 Multiple prefetching strategies
11
- - 🔍 SEO-friendly
11
+ - 🔍 SEO-friendly (works with Wordpress)
12
12
  - 📱 Mobile-friendly with data-saver mode support
13
- - ⚡ Automatic script execution
14
13
  - 🎨 Built-in loading animations
14
+ - 🕰️ Based on History API so you can use native browser navigation
15
+
15
16
 
16
17
  ## Installation
17
18
 
18
19
  ### NPM
20
+
21
+ ```sh
22
+ npm install lightweight-router
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ To use the lightweight router in your project, follow these steps:
28
+
29
+ 1. Import the `startRouter` function from the router module.
30
+ 2. Call the `startRouter` function to initialize the router.
31
+
32
+ Example:
33
+
34
+ ```javascript
35
+ import { startRouter } from "lightweight-router";
36
+
37
+ startRouter({
38
+ onRouteChange: currentRoute => {
39
+ console.log("Route changed:", currentRoute);
40
+ },
41
+ });
42
+ ```
43
+
44
+ ### Direct Import
45
+
46
+ You can also directly import the minified version of the router in your HTML file or paste its content inside a script tag:
47
+
48
+ ```html
49
+ <!DOCTYPE html>
50
+ <html lang="en">
51
+ <head>
52
+ <meta charset="UTF-8" />
53
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
54
+ <title>My App</title>
55
+ </head>
56
+ <body>
57
+ <!-- Your website content -->
58
+ <script src="path/to/dist/router.min.js"></script>
59
+ </body>
60
+ </html>
61
+ ```
62
+
63
+ ## API
64
+
65
+ ### `startRouter(options)`
66
+
67
+ Initializes the router with the given options.
68
+
69
+ #### Parameters
70
+
71
+ - `options` (Object): Configuration options for the router.
72
+ - `onRouteChange` (Function): Callback function to be called when the route changes.
73
+
74
+ ## Examples
75
+
76
+ ### Basic Example
77
+
78
+ ```html
79
+ Your website content
80
+ <script type="module">
81
+ import { startRouter } from "./router.js";
82
+
83
+ startRouter({
84
+ onRouteChange: currentRoute => {
85
+ console.log("Route changed:", currentRoute);
86
+ },
87
+ });
88
+ </script>
89
+ ```
90
+
91
+ ## Server Configuration
92
+
93
+ Configuring your server to return only the route content can make the router much more efficient. Instead of returning the entire page, the server should return only the content for the requested route when it detects a request with the message "onlyRoute".
94
+
95
+ ```javascript
96
+ await fetch(url, { method: "POST", body: "onlyRoute" });
97
+ ```
98
+
99
+ This allows only the changing part of the document to be updated, improving performance and reducing bandwidth usage.
100
+
101
+ Once you configured your server to respond to this type of request, wrap the part of your document that changes in a `router` tag. Inside the `router` tag, render the current initial route inside a `route` tag like this:
102
+
103
+ ```html
104
+ <-- Header menu and parts that don't change -->
105
+ <router>
106
+ <route path="/" style="content-visibility: auto">home content</route>
107
+ </router>
108
+ <-- footer etc.. -->
109
+ ```
110
+
111
+ You can also prerender other important routes by rendering them inside the `router` tag in their appropriate `route` tags for faster loading times:
112
+
113
+ ```html
114
+ <router>
115
+ <route path="/" style="content-visibility: auto">home content</route>
116
+ <route path="/about" style="content-visibility: auto; display:none;">about content</route>
117
+ </router>
118
+ ```
119
+
120
+ In the future you will also be able to pre-render a default route that will be used as 404 by having it at /404 or /default
121
+
122
+ Right now errors are shown without styling as the content of the page.
123
+
124
+ Soon there will be a DenoJS library that will help you deal with all these routes stuff. It will also come with api routes functionality 🔥
125
+
126
+ ## Prefetching
127
+
128
+ By default, links are prefetched when they get in the user's screen using an `IntersectionObserver`. This ensures that the content is loaded in the background before the user clicks on the link, providing a smoother navigation experience.
129
+
130
+ If you have too many links at once or too many requests, you can add the `prefetch="onHover"` attribute to your links or some of them (usually links to huge pages that are not often visited):
131
+
132
+ ```html
133
+ <a href="/archive" prefetch="onHover">Archive</a>
134
+ ```
135
+
136
+ P.S. you can easily test in your website by pasting this minified version into the console.
137
+
138
+ The minified version was created with uglify-js, clean.css and then minified again with https://packjs.com
139
+ The size of the gzipped version was calculated with: https://dafrok.github.io/gzip-size-online/
140
+ It's worth to note that nonethewise Terser give better results than uglify-js. The final uglify version packed by packjs.com was even smaller.
141
+
142
+ ## Browser Support
143
+
144
+ The router supports all modern browsers. Required features:
145
+
146
+ - IntersectionObserver
147
+ - Fetch API
148
+ - History API
149
+
150
+ For older browsers, consider using the following polyfills:
151
+
152
+ - intersection-observer
153
+ - whatwg-fetch
154
+
155
+ ## Performance Tips
156
+
157
+ - Use `content-visibility: auto` on route elements to improve rendering performance
158
+ - Implement server-side partial responses for better bandwidth usage
159
+ - Consider using the `prefetch="onHover"` attribute for less important links
@@ -1 +1 @@
1
- (()=>{let c={},n=async()=>{var e=document.querySelector("router"),t=globalThis.location.pathname;let o=e.querySelector(`route[path="${t}"]`),n=(o||((o=document.createElement("route")).setAttribute("path",globalThis.location.pathname),e.appendChild(o)),document.body.classList.add("loading"),c[globalThis.location.href]);n||(n=await d(globalThis.location.href),c[globalThis.location.href]=n);var r,a=(new DOMParser).parseFromString(n,"text/html"),i=a.querySelector("title"),i=(i&&(document.title=i.textContent),o.innerHTML=a.body.innerHTML,Array.from(o.querySelectorAll("script")));for(r of i){var l=document.createElement("script");r.src?l.src=r.src:l.textContent=r.textContent,r.parentNode.replaceChild(l,r)}e.querySelectorAll("route").forEach(e=>e.style.display="none"),o.style.display="contents",document.body.classList.remove("loading"),window.scrollTo(0,0),s&&s(t)},r=async e=>{c[e.href]||(c[e.href]=await d(e.href))},a=(e,t)=>{e.forEach(e=>{e.isIntersecting&&(e=e.target,c[e.href]||(r(e),t.unobserve(e)))})},i=e=>{var t=e.target.closest("A");t&&t.href&&l(t.href)&&t.origin===location.origin&&(e.preventDefault(),globalThis.history.pushState(null,null,t.href),globalThis.dispatchEvent(new Event("popstate")))};function l(e){if(e&&!e.startsWith("#")&&!e.startsWith("javascript:")){if(e.startsWith("/"))return 1;try{var t=new URL(e,window.location.origin),o=new URL(window.location.href);return o.hostname.replace(/^www\./,"")===t.hostname.replace(/^www\./,"")?o.pathname!==t.pathname||!t.hash:void 0}catch{}}}let s,d=async e=>{e=await t(e);return e.ok?e.text():"Couldn't fetch the route - HTTP error! status: "+e.status},t=async e=>{if(!h){var t=await fetch(e,{method:"POST",body:"onlyRoute"});if(t.ok)return t}return fetch(e)},h=!1,e=(e={})=>{var t,e=e.onRouteChange,e=(e&&(e=e,s=e),document.createElement("style")),e=(e.textContent="body.loading{animation:pulseOpacity 1s infinite alternate}@keyframes pulseOpacity{from{opacity:.8}to{opacity:.3}}",document.head.appendChild(e),document.querySelector("router")),o=globalThis.location.pathname,o=(e||(e=document.createElement("router"),(t=document.createElement("route")).setAttribute("path",o),t.style.contentVisibility="auto",t.innerHTML=document.body.innerHTML,e.appendChild(t),document.body.innerHTML="",document.body.appendChild(e),h=!0),globalThis.addEventListener("popstate",n),document.addEventListener("click",i),document.body.addEventListener("mouseover",e=>{"A"===e.target.tagName&&"onHover"===e.target.getAttribute("prefetch")&&(async e=>{e=e.target;!c[e.href]&&l(e.href)&&await r(e)})(e)}),new IntersectionObserver(a,{root:null,threshold:.5}));(t=>{let o=navigator.connection&&navigator.connection.saveData;document.querySelectorAll("a").forEach(e=>{"onHover"===e.getAttribute("prefetch")||o||l(e.href)||t.observe(e)})})(o)};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>e()):e()})();
1
+ $="(£ì­c={},n=async£ìܵ¨¢t=êð;­¦úè([pÓh=${t}]n=(((o´êð÷ú½(o)÷Æç.addöÛ³¼nÊ(nd(êó³=n¼Ür,a=(ÍDOMParsõ).parseF°mString(n,ýxt/html¢i=a.èötàle¢i=((¾tàlµi.Ý÷¥î=a.¬.î,Array.f°m(¥¹Éé)¼for(r of i){Ül=ßÉé;r«?l«=r«:l.Ý=r.Ý,r.paùïNodÐChild(l,rØú¹äé.fÔ=>ú²nëeé÷¥²c¡sÑÆç.ùmo·öÛ¢Ïsc°llTo(0,0÷sÞs(tØ,r=âËÊ(Ë=×dªØ,a=ô,t)ìúfÔìúisIÀngÞôí,ËÊ(rô÷Õun®))±Ø,i=eìÜtí.closeçöAé;tÞÕóÞl(Õó)ÞÕÈÒ=lüÈÞ(úpù·ïDefault(ºhiçory.pushStaý(¸¸ÕóºdispÓchE·ï(ÍE·ïö¯é)Ø;functië ){ifô©#é©javaÉ:é){ Öhö/é)á1;try{Üt=ÍURLô,ÏlüÈ÷¦ÍURL(Ïlüó¼á¥¤Ò=Õ¤?¥ð!ÒÕðÊ!Õhash:void 0}cÓch{}}}­s,d=âµ×tô¼áúok?úýxt£:Couldn't Ì the ä - HTTP õ°r! çÓus: +úçÓus},t=â !h){Üt=×Ìô,{mÚhod:POSTѬ:ëlyRouý}¼ Õok)át}áÌôØ,h=!1,µô={})ìÜt,µúëRouýChange,µôÞô=e,s=e÷ßçyleé÷µ(úÝ=¬.Û{animÓië:¶ 1s infiniý alýrnaý}@keyframes {f°m§8}to§3}}Ѿhead.½ô÷¨é÷¦êð,¦ôÊô=ßär¢(t´o÷Õçylúc¡Visibilày=autoÑÕî=òî,ú½(t÷òî=Ñò½ô÷h=!0ºÙ¯Ñn÷¾ÙclickÑi÷òÙmouseovõÑôìAÒí.tagNameÞ»í.¿Þ(âeí;!ËÞlªÞ×rô±ô±÷ÍIÀëObsõvõ(a,{°ot:¸thùshold:.5})¼(tì­¦naÁÞnaÁ.sa·DÓa;¾¹aé.fÔì»=ú¿ÊoÊlªÊÕ®±±(oØ;ÛÒ=¾ùadyStaý?¾ÙDOMC¡LoadedÑ(£=>e£)):e(±(¼";l="if(ëýï÷()hoÂéo.o={oÎ:.¾èöärÞ!Öhö(úó).srcbodylÚ obsõ·ôpopçaýroØ)çylÇ=÷c[êó]=ßäÅÓhÑe=pulseOÎvenull,èAllö÷glû.ëHovõÒ);aãlddþgÚAåpùÌénýrsectivigÃctiëÄwww./,Óor.cëneçnamÐ(/^é).sÚAåpòclassLiúdisplayoriginscript||c[úó]fÚchnew pacàywindow.úùplace,==atorEach(ôt.úçartsWàawaà )}addEveæetloadingvar ýxtCëýï&&dñmeïöitùturn async eìppendChirouýttribuýöïLisýnõöstquõør)glû.lüon=>{=útargetinnõHTMLntpathnameþcùaýEledþbody.hùf(eer(),ySelectoree.obalThisocation.teocument.".split('');_=" ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ";for(i=0;i<95;i++){$=$.split(_[i]).join(l[i])};eval($.replace(//g,'"').replace(//g,'\\').replace(//g,String.fromCharCode(10)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lightweight-router",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "main": "dist/router.min.js",
5
5
  "scripts": {
6
6
  "dev": "npx http-server src -o",