Redirect the page and prevent the rest of the page from loading and script from execution

浪尽此生 提交于 2019-12-10 16:38:32

问题


I need to redirect page when it starts loading (e.g. the head part of the page loaded) and once it is redirected prevent/stop the rest of the page content from loading and the rest of the script from execution.

If I place this code (window.location = "/other-page-url";) at the first line after opening HEAD tag and redirect page to another one, will it stop execution of next going scripts? I want to be sure that if there are, let's say, some counter script called on the second line, just after redirection, it will not execute.

May be JavaScript has some method which stops page loading/rendering?


回答1:


Once you have redirected the user to a different page, the current page will stop execution immediately.




回答2:


You can do this before any Javascript is executed using a <meta> tag in your <head> before any <script> tags:

<meta http-equiv="Refresh" content="0; url=http://www.example.com/">

This would redirect the browser to example.com as soon as it encounters the tag.




回答3:


I tested this extensively in Chrome on Windows, taking notes from the discussion at https://stackoverflow.com/a/24070373/5749914. To expound on Joseph Silbur's answer:

Once you have redirected the user to a different page, the current page will stop execution immediately.

JavaScript within the head tag is executed before any script tags in the body of the document. Although Chrome make requests for script tags within the body tag, those scripts are not executed. The only code that is executed is JavaScript within the head tag.

Also of note, Chrome fires the DOMContentLoaded event before redirecting the page. This doesn't matter unless you have something listening specifically to that event.

So yeah, window.location = "/other-page-url" works, so long as it's the only code in the head tag.



来源:https://stackoverflow.com/questions/8759768/redirect-the-page-and-prevent-the-rest-of-the-page-from-loading-and-script-from

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