Is it possible to run JavaScript code before Meta refresh

不想你离开。 提交于 2019-12-24 09:40:19

问题


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"


回答1:


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">



回答2:


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.



来源:https://stackoverflow.com/questions/17205850/is-it-possible-to-run-javascript-code-before-meta-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!