Skip to content

Instantly share code, notes, and snippets.

@RobertFischer
Created October 4, 2017 20:00
Show Gist options
  • Save RobertFischer/69bd60429e4eea4341903888c65ad44a to your computer and use it in GitHub Desktop.
Save RobertFischer/69bd60429e4eea4341903888c65ad44a to your computer and use it in GitHub Desktop.
Nifty Trick for Loading CSS in Pure Elm
module Main exposing (main)
import Navigation exposing (program, Location)
import Platform.Cmd as Cmd exposing (Cmd)
import Platform.Sub as Sub exposing (Sub)
import Html exposing (Html)
import Html.Attributes as Attr
import Html.Events as Event
import Routes exposing (Route(..))
import RemoteData exposing (..)
import RemoteData.Infix exposing (..)
import Cmd.Extra exposing (..)
main : Program Never Model Msg
main =
program (Routes.parseLocation >> GoToRoute)
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
type alias Model =
{ currentRoute : Route
, nextRoute : Maybe Route
}
type Msg
= GoToRoute Route
init : Location -> ( Model, Cmd Msg )
init loc =
( { currentRoute = InitialRoute
, nextRoute = Nothing
}
, message << GoToRoute <| Routes.parseLocation loc
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GoToRoute route ->
( { model | currentRoute = route }, fetchRoute route )
fetchRoute : Route -> Cmd Msg
fetchRoute route =
Cmd.none
view : Model -> Html Msg
view model =
Html.div [ Attr.id "top-most", Attr.class "container" ] [ viewForRoute model.currentRoute ]
viewForRoute : Route -> Html Msg
viewForRoute route =
case route of
InitialRoute ->
addCss
HomeRoute ->
Html.text "This is the home page"
RouteNotFound ->
Html.text "Could not find what you are looking for."
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
addCss : Html msg
addCss =
Html.div [] <|
List.map addCssLink
[ "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
]
addCssLink : String -> Html msg
addCssLink css =
Html.node "script"
[ Attr.type_ "text/javascript" ]
[ Html.text ("""
document.body.hidden=true;
var link=document.createElement('link');
link.href='""" ++ css ++ """'; link.rel='stylesheet';
document.getElementsByTagName('head')[0].appendChild(link);
window.setTimeout(function () { document.body.hidden=false; }, 0);
""") ]
@RobertFischer
Copy link
Author

The idea is to have an "initial page" which loads before anything else. That page shoves a bunch of <link> tags to the CSS files into the <head> of the document, and then is immediately replaced by the actual contents that you want to load.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment