Trying to lazy load this code:
<script async src="https://comments.app/js/widget.js?3" data-comments-app-website="TvibSQx_" data-limit="5" data-color="29B127" data-dislikes="1" data-colorful="1"></script>
Can lazy load an external JavaScript like this:
<script type="text/javascript">
window.addEventListener('scroll', function(e) {
var currentScroll = document.scrollingElement.scrollTop;
var telegram_target = document.getElementById('telegram');
if( telegram_target && (currentScroll > telegram_target.getBoundingClientRect().top - 150) ) {
$.getScript("https://comments.app/js/widget.js?3")
}
}, false);
</script>
Or can do it like this:
<script type="text/javascript">
window.addEventListener('scroll', function(e) {
var currentScroll = document.scrollingElement.scrollTop;
var telegram_target = document.getElementById('telegram');
if( telegram_target && (currentScroll > telegram_target.getBoundingClientRect().top - 150) ) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://comments.app/js/widget.js?3";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
}, false);
</script>
But is it possible to lazy load the external JavaScript file with the data parameters
data-comments-app-website="TvibSQx_" data-limit="5" data-color="29B127" data-dislikes="1" data-colorful="1"
2
Answers
You can add data attributes to your script tag using the
setAttribute()
method like this:Or if you would like to use jQuery, you can do it like this:
**** UPDATE: Here is a complete example. More information on the Intersection Observer API
This is the easy way
Add the Following Code into Head.
Wrap the code in lazyhtml wrapper.
LazyHTML Git