Is it possible to run JavaScript code before Meta

2019-07-31 19:21发布

All the while, we are using this realiable website redirection HTML/JavaScript code

<!DOCTYPE HTML>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="refresh" content="1;url=https://www.nosuchwebsite.com">
        <script type="text/javascript">
            window.location.href = "https://www.nosuchwebsite.com"
        </script>
        <title>Page Redirection</title>
    </head>
    <body>
        <!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
        If you are not redirected automatically, follow the <a href='https://www.nosuchwebsite.com'>nosuchwebsite</a>
    </body>
</html>

Now, we would like to have Google Analytics tracking code executed, before redirection.

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

I realize, meta "refresh" may execute earlier than JavaScript tracking code. I was wondering, whether is there any way to make Google Analytics tracking code, to run before meta "refresh"

2条回答
萌系小妹纸
2楼-- · 2019-07-31 20:07

Simply increase the number of seconds for meta refresh command and it will wait for that long before redirecting to the new page. That will allow your JavaScript to execute meanwhile.

<meta http-equiv="refresh" content="1;url=https://www.nosuchwebsite.com">
                                    ^

can be

<meta http-equiv="refresh" content="3;url=https://www.nosuchwebsite.com">
查看更多
SAY GOODBYE
3楼-- · 2019-07-31 20:23

Or don't use meta refresh and use Javascript refresh and have the meta refresh in a <noscript> block for good measure, as when Javascript is disabled the Analytics won't work anyways.

查看更多
登录 后发表回答