Improve CSS and JS loading Asset.html.twig #1120
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Using the defer attribute in script tags is generally considered better than placing JavaScript at the end of the HTML file because it offers several advantages related to page loading and performance:
Improved Parsing and Loading Performance:
When a script tag uses defer, the browser downloads the script file asynchronously, without pausing the HTML parsing.
Scripts placed at the end of the file still block rendering at the point they are encountered until fully downloaded and executed.
Maintainability and Readability:
Scripts using defer can be placed in the HTML , clearly defining dependencies upfront rather than scattering script tags throughout the HTML file.
This improves maintainability, readability, and makes it easier for developers to manage and track JavaScript dependencies.
Automatic Execution Order:
defer scripts execute in the order they appear in the HTML document, which is particularly useful when scripts depend on each other.
Placing scripts manually at the end of the file can become error-prone as the number of scripts grows.
Better Handling of Dependencies:
Using defer ensures scripts run only after the DOM has fully loaded (DOMContentLoaded event), removing the need for manual event listeners such as DOMContentLoaded or window.onload.
Scripts at the end of HTML might still require explicit event listeners to ensure DOM readiness.
Loading a print CSS file dynamically via JavaScript rather than using has several advantages, primarily in terms of page loading performance and user experience:
Modern browsers typically download print CSS files even if the user doesn't print the page. This adds an unnecessary HTTP traffic increasing initial page load time.
Loading via JavaScript solves this issue by downloading the print CSS file after page is loaded.