I want to load an inline JavaScript after the page has fully loaded. The reason is, that the scripts loads an external JS file which I don't want to block the rendering of the page.
This is the whole code:
<script type="text/javascript">
(function () {
var _tsid = 'XXXX';
_tsConfig = {
'yOffset': '0', // offset from page bottom
'variant': 'custom_reviews', // default, reviews, custom, custom_reviews
'customElementId': 'MyCustomTrustbadge', // required for variants custom and custom_reviews
'trustcardDirection': 'bottomLeft', // for custom variants: topRight, topLeft, bottomRight, bottomLeft
'customBadgeWidth': '', // for custom variants: 40 - 90 (in pixels)
'customBadgeHeight': '', // for custom variants: 40 - 90 (in pixels)
'disableResponsive': 'false', // deactivate responsive behaviour
'disableTrustbadge': 'false' // deactivate trustbadge
};
var _ts = document.createElement('script');
_ts.type = 'text/javascript';
_ts.charset = 'utf-8';
_ts.async = true;
_ts.src = '//widgets.trustedshops.com/js/' _tsid '.js';
var __ts = document.getElementsByTagName('script')[0];
__ts.parentNode.insertBefore(_ts, __ts);
})();
</script>
I know that I could maybe use $(document).ready
. But I don't know how.
CodePudding user response:
The reason is, that the scripts loads an external JS file which I don't want to block the rendering of the page.
Adding the defer
attribute to the script element will defer execution until the DOM is ready while allowing the script to be downloaded in parallel.
CodePudding user response:
Another solution would be to enclose the execution of your code in an EventListener wich executes if the DOMContent is fully loaded.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var _tsid = 'XXXX';
_tsConfig = {
'yOffset': '0', // offset from page bottom
// default, reviews, custom, custom_reviews
'variant': 'custom_reviews',
// required for variants custom and custom_reviews
'customElementId': 'MyCustomTrustbadge',
// for custom variants: topRight,
// topLeft, bottomRight, bottomLeft
'trustcardDirection': 'bottomLeft',
'customBadgeWidth': '', // for custom variants: 40 - 90 (in pixels)
'customBadgeHeight': '', // for custom variants: 40 - 90 (in pixels)
'disableResponsive': 'false', // deactivate responsive behaviour
'disableTrustbadge': 'false' // deactivate trustbadge
};
var _ts = document.createElement('script');
_ts.type = 'text/javascript';
_ts.charset = 'utf-8';
_ts.async = true;
_ts.src = '//widgets.trustedshops.com/js/' _tsid '.js';
var __ts = document.getElementsByTagName('script')[0];
__ts.parentNode.insertBefore(_ts, __ts);
});
</script>