mimmovele
mimmovele

Reputation: 21

How to programmatically block/execute javascript blocks?

Let's have a generic snippet of javascript code such as:

<!-- Google Analytics -->
<script async src='//www.google-analytics.com/analytics.js'></script>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

Is there a way to avoid that this script executes when page loads? And later activate it (via javascript) as if it were started from the beginning?

A solution would be to add type="text/plain" to <script> tags to stop the execution. To activate them later we could create an empty <script type="text/javascript"></script> and put the content of the modified script into it (for the script tag with src attribute, we could just create a <script type="text/javascript" src="..."></script> with the same src attribute of the modified one) and add it to the page.

But what I'm looking for is to get the same result w/o modifying the script itself, maybe including it (as it is) into another tag, or rather than converting it into a string and let it being inserted into the page with jQuery.parseHTML().

Any ideas? Any helps would be appreciated.

Thanks!

Upvotes: 1

Views: 1297

Answers (1)

Konstantin
Konstantin

Reputation: 3450

function runMeLater() {
   var script = document.createElement('script');
      script.setAttribute('src', '//www.google-analytics.com/analytics.js');
      document.body.appendChild(script);

    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-XXXX-Y', 'auto');
    ga('send', 'pageview');
}

Upvotes: 2

Related Questions