Search code examples
javascriptspringthymeleafbootstrap-5

bootstrap script has not finished loading before the tooltip initialization


I have a simple one page website with bootstrap 5 set up using spring boot with thymeleaf.

On this page I want e.g. to use the bootstrap tooltip. The problem is that the function to initialize the tooltip fires before the bootstrap script has finished loading so there will be an error and the page will not load correctly.

<head>
  ... // css and meta omitted for brevity

  <script th:src="@{/js/bootstrap.bundle.min.js}" async="true"></script>
  
</head>

<body>

  ... // page content

  <script>
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })
  </script>
</body>

I tried to place the bootstrap script

  • in the head section
  • with async attribute
  • with defer attribute
  • a combination of the attributes
  • in the body section directly before the tooltip init script

but nothing prevents the second script to fire before the first script has finished loading.

I have read the HTML spec here but in the end I'm not sure if the loading of the script is truly the problem.

Has someone an idea to definitly prevent this error?


Solution

  • Finally solved this problem.

    I put all the javascript code in a seperate js-file. Then I load this file after the bootstrap file at the end of the body and everything works fine.

    <head>
      ... //css and meta
    </head>
    
    <body>
      ... // page content
    
      <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
      <script th:src="@{/js/myfunction.js}"></script>
    
    </body>