How to UP Page Speed With Widget Defer?

Is there a way to defer a widget in the footer?

I have an external API in a footer widget which is slowing down my page. It is not needed until the page is loaded.

The caching plugin I use (W3 Total Cache) gives me the option to defer other scripts, but not scripts directly coded into the widget.

What is the best way to manually defer custom code API that is in the WordPress widget area of a footer?

Like This

enter image description here

enter image description here

<script type="text/javascript">
baseUrl = "https://widgets.cryptocompare.com/";
var scripts = document.getElementsByTagName("script");
var embedder = scripts[ scripts.length - 1 ];
var cccTheme = {"General":{"background":"#ffffff14","borderWidth":"0","borderColor":"none"},"Tabs":{"background":"#ffffff08","color":"#eee","activeBackground":"#ffffff14","activeColor":"#fff"},"Row":{"color":"#eee","borderColor":"#016ac1"},"Trend":{"colorDown":"#b7b6b6","colorUp":"#50dcb6","colorUnchanged":"#dddddd"},"Conversion":{"color":"#006ac1"}};
(function (){
var appName = encodeURIComponent(window.location.hostname);
if(appName==""){appName="local";}
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
var theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&tsyms=USD,BTC,GBP,CNY';
s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + "app=" + appName;
embedder.parentNode.appendChild(s);
})();
</script>

3 Answers
3

Your code shows an inline script, which adds a new script tag to the DOM, which probably slows down your website’s loading time. This is not an inline script tag then. Try adding this line s.defer = true; after s.async = true; to add the defer attribute to your script tag. It should then look like this:

var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.defer = true; //add this line
var theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&tsyms=USD,BTC,GBP,CNY';
s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + "app=" + appName;
embedder.parentNode.appendChild(s);

This should result in adding a new script tag (named s in your code) to all the scripts the page will load and it should look like this:

<script type="text/javascript" async defer src="https://widgets.cryptocompare.com/serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;tsyms=USD,BTC,GBP,CNY"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *