Skip to content

Commit

Permalink
Cache video.js in background and require it only where needed
Browse files Browse the repository at this point in the history
  • Loading branch information
LostKobrakai committed Dec 31, 2024
1 parent 9c79f55 commit 582246f
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 5 deletions.
13 changes: 13 additions & 0 deletions assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,16 @@ liveSocket.connect();
window.liveSocket = liveSocket;

handleDarkMode();

if ("serviceWorker" in navigator) {
// Register a service worker hosted at the root of the
// site using the default scope.
navigator.serviceWorker
.register("/assets/serviceworker.js", { scope: "/" })
.then(
(registration) => console.log("Service worker registration succeeded."),
(error) => console.error(`Service worker registration failed: ${error}`),
);
} else {
console.error("Service workers are not supported.");
}
69 changes: 69 additions & 0 deletions assets/js/serviceworker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"use strict";

const version = "20241231";
const staticCacheName = "static-" + version;
const cacheList = [staticCacheName];

async function updateStaticCache() {
let staticCache = await caches.open(staticCacheName);
staticCache.addAll([
"/assets/video.js",
"/assets/app.css",
"/assets/app.js",
"/images/signee.png",
"/images/pfeil.png",
"/images/avatar.jpg",
"/font/noway-regular-webfont.woff",
"/font/noway-regular-webfont.woff2",
"/font/Virgil.woff2",
]);
}

async function clearOldCaches() {
let keys = await caches.keys();
return Promise.all(
keys
.filter((key) => !cacheList.includes(key))
.map((key) => caches.delete(key)),
);
}

addEventListener("install", (installEvent) => {
installEvent.waitUntil(updateStaticCache());
skipWaiting();
});

addEventListener("activate", (activateEvent) => {
activateEvent.waitUntil(clearOldCaches());
clients.claim();
});

addEventListener("fetch", (fetchEvent) => {
let request = fetchEvent.request;
let url = new URL(request.url);

// Only deal with requests to my own server
if (url.origin !== location.origin) {
return;
}

// Only deal with GET requests
if (request.method !== "GET") {
return;
}

// For HTML requests, try the preload first, then network, fall back to the cache, finally the offline page
if (
request.mode === "navigate" ||
request.headers.get("Accept").includes("text/html")
) {
return;
}

// For non-HTML requests, look in the cache first, fall back to the network
fetchEvent.respondWith(
caches.match(request).then((responseFromCache) => {
return responseFromCache || fetch(request);
}),
);
});
2 changes: 1 addition & 1 deletion config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ config :bun,
install: [args: ~w(install), cd: Path.expand("../assets", __DIR__), env: %{}],
default: [
args:
~w(build js/app.js js/storybook.js js/video.js --format=iife --outdir=../priv/static/assets --external /fonts/* --external /images/*),
~w(build js/app.js js/storybook.js js/video.js js/serviceworker.js --format=iife --outdir=../priv/static/assets --external /fonts/* --external /images/*),
cd: Path.expand("../assets", __DIR__),
env: %{}
],
Expand Down
8 changes: 7 additions & 1 deletion lib/kobrakai_web/components/layouts/root.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}>
</script>
<script async phx-track-static type="text/javascript" src={~p"/assets/video.js"}>
<script
:if={assigns[:video_js]}
defer
phx-track-static
type="text/javascript"
src={~p"/assets/video.js"}
>
</script>

<script type="text/javascript">
Expand Down
10 changes: 9 additions & 1 deletion lib/kobrakai_web/endpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ defmodule KobrakaiWeb.Endpoint do
gzip: true,
at: "/",
from: :kobrakai,
only: KobrakaiWeb.static_paths()
only: KobrakaiWeb.static_paths(),
headers: {__MODULE__, :static_headers, []}

# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
Expand Down Expand Up @@ -68,4 +69,11 @@ defmodule KobrakaiWeb.Endpoint do
|> Phoenix.Controller.put_router_url(uri)
|> Phoenix.Controller.put_static_url(uri)
end

def static_headers(conn) do
case conn.request_path do
"/assets/serviceworker.js" -> [{"Service-Worker-Allowed", "/"}]
_ -> []
end
end
end
2 changes: 1 addition & 1 deletion lib/kobrakai_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ defmodule KobrakaiWeb.Router do
get "/kolumne/:id", BlogController, :show

get "/videos", VideoController, :index
get "/videos/:id", VideoController, :show
get "/videos/:id", VideoController, :show, assigns: %{video_js: true}

get "/photography", CustomController, :photography
get "/werdegang", CustomController, :cv
Expand Down
6 changes: 5 additions & 1 deletion lib/kobrakai_web/views/page_html/home.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
]}
href={url(@conn, ~p"/videos/#{video.id}")}
>
<.image class="border-white border-2 mb-1" src={video.thumbnail} size={{640, 0}} />
<.image
class="border-white border-2 mb-1 aspect-[16/9]"
src={video.thumbnail}
size={{640, 0}}
/>
<div class="text-gray-500 dark:text-gray-400 text-sm">
{Calendar.strftime(video.date, "%d.%m.%Y")}
</div>
Expand Down

0 comments on commit 582246f

Please sign in to comment.