Search code examples
bootstrap-4deferred-loading

Bootstrap-4 scripts best location and scripts' tags


An old topic with lots of discussions... I read many of them but still not sure...

What is the best place and best script's tags (defer/async) to locate the bootstrap-4 JS scripts for the best performance?

In Bootstrap documentation: "Place the following s near the end of your pages,right before the body closing tag

</body>

They don't use any script tags (defer/async)

I read about the scripts tags, Some wrote that locating the script before the body closing tag is like locating the heading with "defer" tag. (except for the old browsers) some say "performance would be better if the scripts are still at the end, as they will be downloaded later"

So is the following the best practice ???

Locating jquery/popper/bootstrap before the body closing tag, jquery first and using defer to popper.min.js and to bootstrap.min.js?

<body>
......
<script  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script defer src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" ></script>
</body>

Or just doing as in the bootstrap documentation without the "defer" tag??


Solution

  • Put at the end is the best practice, you can even write script after the close of the body: an html is loaded from the top to the button, when a browser reach a script element it downloads (and wait) the source, so if you put it at the end, the page will load and then the js will downloaded. Remember that js is needed to make the view dynamic so until the page is loaded you don't need functionalities like: click on a dropdwon and see its content. Defer/async are just a way to achieve the same result, but it's not exactly the same.