Search code examples
javascripthtmlpagespeeddeferred-loading

Defer loading of HTML widget with script tag


I have a call-to-action widget that I'd like to display above the fold for mobile devices. However, Google PageSpeed is penalizing me for loading a widget before the main content loads. I tried embedding the widget in a script tag with a defer attribute, but now the widget is not loading at all.

With this code, I got a Google PageSpeed score of 99 for mobile, but the widget does not load.

<?php if(is_mobile()) : ?>
  <script  type="text/html" defer>
    <div class="widget">Call Now</div>
  </script>
<?php endif; ?> 

With this code, the widget does load in mobile devices, but my Google Page Speed score falls to 93.

<?php if(is_mobile()) : ?>
    <div class="widget">Call Now</div>
<?php endif; ?> 

Here is the full HTML widget, along with the fix suggested by @randy-casburn. The widget does not load with this code either.

<?php if(is_mobile()) : ?>
  <script defer>document.addEventListener('DOMContentLoaded', ()=> {document.querySelector('body').innerHTML += '<div id="mobile-cta" class="widget-wrapper widget_text"><div class="widget-title"><h3>Call or Email Now</h3></div><div class="textwidget"><span class="desktop-number">During office hours: 999.999.9999<br /></span><span class="mobile-number">During office hours: <a href="tel:9999999999" onClick="javascript:_gaq.push(['_trackPageview', '/widgetTel']);">999.999.9999</a><br /></span>After hours:  <a href="mailto:email@email.com" onClick="javascript:_gaq.push(['_trackPageview', '/widgetEmail']);">email@email.com</a><br /></div></div>';}</script>
<?php endif; ?> 

Edit: added example of penalized code.


Solution

  • Do:

    document.addEventListener('DOMContentLoaded', ()=> {
      document.querySelector('body').innerHTML += '<div class="widget">Call Now</div>';
    });
    

    This will allow the DOM to be constructed first and then add your div and that should do the trick.