Problem with select2 using liveview

First, I will review the structure of the project.
To facilitate understanding

template/layout/root.html.leex

<link rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/select2.min.css") %>"/>

<script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/select2.min.js") %>"></script>

project_web/live/example_live/form_component.html.leex

    <div class="form-group" phx-update="ignore">
      <label>Ofensor</label>
      <div class="select2-purple" phx-update="ignore">
            <%= multiple_select(f, :ofensor, @priority_risk, prompt: "Select options", class: "form-control select2 select2-hidden-accessible", multiple: "multiple", style: "width: 100%;" ) %>
            <%= error_tag f, :ofensor %>
      </div>
    </div>

<script>
  $(function () {
    //Initialize Select2 Elements
    $('.select2').select2()

    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })
  })
</script>

project_web/live/example_live/index.html.leex

            <span>
            <%= live_patch "New", to: Routes.notification_problem_index_path(@socket, :new), class: "btn btn-block bg-gradient-primary" %>
            </span>

The Big Problem is…
When I start a new session at the address
http://localhost:4000/problem and I click the “New” button it can’t load the css.

But if you start a new session directly at http://localhost:4000/problem/new, css loads perfectly.
Problem seems to be with liveview.
Has anyone ever experienced this?

You should move the Select2 initialization from the <script> tag into a liveview hook. Your <script> code won’t get run on live navigation.

Is there an easier way to do this?

Thanks
I managed to add.
That way it worked.

If anyone needs it, follow below.

/assets/js/app.js


let Hooks = {}
Hooks.Awesomhook = {
  mounted() {

    $(function () {
        //Initialize Select2 Elements
        $('.select2').select2()
    
        //Initialize Select2 Elements
        $('.select2bs4').select2({
          theme: 'bootstrap4'
        })
      })

  }
}

let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}, hooks: Hooks})