Unnecessary JS on Initial Load
JavaScript can also cause performance issues. If our module uses JS for operations, performance problems can arise if the JS is loaded synchronously when not needed.
To optimize the inclusion and execution of JavaScript files, we can adopt several strategies.
JS Loading Optimization
We should distinguish the triggers that might be needed and include the JS only when necessary. The most common triggers include:
- Viewing a specific element on the page (viewport trigger)
- Interaction with elements
Practical Examples for Each Trigger
Viewing a Specific Element on the Page
Suppose we want to include a widget that displays reviews of our site and position it near the footer. It would be inefficient to load the JS code when the page loads or even use defer to load it at the end. Instead, we can load the JS only when the user is about to reach the footer.
Implementation:
To implement this logic, Ector offers an integrated function that allows it to be done easily.
- Create the Div that will act as a Trigger:
<div in-viewport v-id="widget"></div>
- Include the Script with the same v-id and type
text/viewport
:
<script type="text/viewport" v-id="widget" src="https://url.com/widget.js"></script>
This way, the JS will load only when the element becomes visible on the page.
Interaction with Elements
This trigger assumes that to load a specific script, we must first interact with the elements. For example, it would be inefficient to load the search engine if the user does not perform a search. We load the widget only when the user clicks on the search field.
Implementation:
We connect to the event or series of events that act as triggers and include the JS file:
<script>
document.getElementById('search').addEventListener('click', function() {
var script = document.createElement('script');
script.src = 'https://url.com/search.js';
document.head.appendChild(script);
});
</script>
Conclusion
Optimizing the loading of JS files is essential for improving site performance. By loading the files only when necessary, the initial page load is reduced, enhancing the user experience. Use triggers such as viewing elements on the page or user interactions to dynamically load JS files only when needed.