简体   繁体   English

在第一次页面加载时运行一个函数而不是在javascript中页面刷新

[英]Run a function on first time page load not on page refresh in javascript

I would like a function to be executed only on the first page load and not when page is refreshed. 我希望只在第一页加载时执行一个函数,而不是在刷新页面时执行。

For example, it should not execute when the user clicks on the submit button, or on other page refresh. 例如,当用户单击提交按钮或其他页面刷新时,它不应该执行。

I can avoid it in .net by using the ispostback property, but how can I do this in JavaScript? 我可以通过使用ispostback属性在.net中避免它,但是如何在JavaScript中执行此操作?

So you want to catch only the first page view. 所以你想只捕获第一页的视图。 It is also known as unique page view . 它也称为唯一页面视图 And then there are the page views, that are incremented at each page reload. 然后是页面视图,在每次页面重新加载时递增。

The first one should be tracked managing the session of the visit (for example using a cookie). 应该跟踪第一个管理访问的会话(例如使用cookie)。 The first time the page is visited, a cookie is set and the counter incremented. 第一次访问页面时,会设置cookie并且计数器会递增。 If the page is visited again if the cookie is already set the counter will not be incremented. 如果已经设置了cookie,则再次访问该页面,计数器将不会递增。 Unless the cookies have been deleted and the user has changed the browser. 除非已删除cookie并且用户已更改浏览器。

The second one will be incremented over and over again at each page refresh. 第二个将在每次刷新页面时反复递增。 Easly achived via javascript. 通过javascript轻松实现。 To manage programmatically the page refresh status, I suggest you this answer . 要以编程方式管理页面刷新状态,我建议您回答这个问题 To manage dynamically the execution of a script, I suggest you the ClientScriptManager . 为了动态管理脚本的执行,我建议您使用ClientScriptManager

Since you use asp and check for postback is ok for you, just render client-side flag; 因为你使用asp并检查回发是否合适,只需渲染客户端标志;

in aspx: 在aspx中:

<script type="text/javascript">window.ispostback = <%= Page.IsPostBack %>;</script>

in client script: 在客户端脚本中:

if (!window.ispostback) {
   // do stuff
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM