Skip to content

Commit 3f2d5ba

Browse files
committed
Add loading spinner to HomeLive
Add a loading spinner to HomeLive so that it does not attempt to load two images and take a long time to connect the LiveView. This will prevent the static render from loading an image and blocking the LiveView connection until said image is loaded. Once the LiveView is connected an img will be rendered on the screen. Locally this was prone to a flash of unstyled content which I really don't like but I am curious if that's not a thing when deployed. So I am going to push this and take a look, but I should probably figure out why the loading spinner flashes without any styling briefly.
1 parent 2e47ad2 commit 3f2d5ba

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

Diff for: lib/samuel_willis_web/live/HomeLive.ex

+25-5
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,31 @@ defmodule SamuelWillisWeb.HomeLive do
1313
%{name: "house.jpg", alt: "Image of a house"}
1414
]
1515

16+
def mount(_params, _session, socket) do
17+
{:ok, assign(socket, :image, Enum.random(@images))}
18+
end
19+
1620
def render(assigns) do
1721
~H"""
18-
<div class="flex flex-col items-center sm:grid sm:grid-cols-2 sm:gap-6 space-y-6">
19-
<.home_image />
22+
<div class="flex-1 flex flex-col items-center sm:grid sm:grid-cols-2 sm:gap-6 space-y-6">
23+
<img :if={connected?(@socket)} src={~p"/images/#{@image.name}"} class="w-96" alt={@image.alt} />
24+
<div :if={not connected?(@socket)} class="w-96 flex justify-center">
25+
<svg
26+
class="animate-spin h-5 w-5"
27+
xmlns="http://www.w3.org/2000/svg"
28+
fill="none"
29+
viewBox="0 0 24 24"
30+
>
31+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
32+
</circle>
33+
<path
34+
class="opacity-75"
35+
fill="currentColor"
36+
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
37+
>
38+
</path>
39+
</svg>
40+
</div>
2041
2142
<nav class="flex flex-col items-center">
2243
<ul class="space-y-4 text-xl font-bold">
@@ -56,11 +77,10 @@ defmodule SamuelWillisWeb.HomeLive do
5677
"""
5778
end
5879

59-
def home_image(assigns) do
60-
assigns = assign(assigns, :image, Enum.random(@images))
80+
attr :image, :map, required: true
6181

82+
def home_image(assigns) do
6283
~H"""
63-
<img src={~p"/images/#{@image.name}"} class="w-96" alt={@image.alt} />
6484
"""
6585
end
6686
end

0 commit comments

Comments
 (0)