mozilla

Revision 351069 of Использование кэширования в Firefox 1.5

  • URL ревизии: en/Using_Firefox_1.5_caching
  • Заголовок ревизии: Using Firefox 1.5 caching
  • ID ревизии: 351069
  • Создано:
  • Автор: torbasow
  • Это текущая версия? Нет
  • комментировать
Метки: 

Содержание версии

 

Введение

Firefox 1.5 использует кэширование целых Web-страниц, включая их JavaScript-состояния, в рамках сессии браузера. Переходы по посещённым страницам вперёд-назад не требуют загрузки страниц, а JavaScript-состояния сохраняются. Эта функция, обозначаемая иногда как bfcache (Back-Forward Cache), делает навигацию по страницам очень быстрой. Такое кэшированное состояние сохраняется, пока пользователь не закроет браузер.

Есть случаи, в которых Firefox не кэширует страницы. Вот некоторые обычные программные причины того, что страница не кэширована:

  • страница использует обработчик unload или beforeunload;
  • страница устанавливает заголовок «cache-control: no-store».
  • доступ к сайту происходит по протоколу HTTPS, а страница устанавливает по меньшей мере один из следующих заголовков:
    • «Cache-Control: no-cache»
    • «Pragma: no-cache»
    • с заголовком «Expires: 0» or «Expires» со значением даты, лежащим в прошлом относительно значению заголовка «Date» (если только не указан также заголовок «Cache-Control: max-age=»);
  • страница не полностью загрузилась, когда пользователь ушёл с неё, или имеет прерванные сетевые запросы по другим причинам (например, XMLHttpRequest));
  • страница имеет работающие IndexedDB-транзакции;
  • страница верхнего уровня содержит фреймы (например, {{ HTMLElement("iframe") }}), которые не кэшируются по одной из перечисленных здесь причин;
  • страница находится в фрейме и пользователь загружает новую страницу в этот фрейм (в этом случае, когда пользователь уходит со с этой страницы, последнее загруженное в фреймы содержимое есть то, что закэшировано).

Эта новая функция кэширования меняет поведение загрузки страницы, так что Web-авторы могут захотеть:

  • узнать, когда на страницу происходит переход (когда она загружается из пользовательского кэша);
  • определить поведение страницы, когда пользователь уходит со страницы (позволяя всё же странице быть закэшированной).

Это позволяют сделать два новых события браузера.

Новые события браузера

Если вы используете эти новые события, ваши страницы продолжат правильно отображаться в других браузерах (мы протестировали старые версии Firefox, Internet Explorer, Opera и Safari), а при загрузке в Firefox 1.5 добавится новая функциональность кэширования.

Примечание: as of 10-2009 development versions of Safari added support for these new events (see the webkit bug).

Standard behavior for Web pages is:

  1. User navigates to a page.
  2. As the page loads, inline scripts run.
  3. Once the page is loaded, the onload handler fires.

Some pages include a fourth step. If a page uses an unload or beforeunload handler, it fires when the user navigates away from the page. If an unload handler is present, the page will not be cached.

When a user navigates to a cached page, inline scripts and the onload handler do not run (steps 2 and 3), since in most cases, the effects of these scripts have been preserved.

If the page contains scripts or other behaviors that fire during loading that you want to continue to execute every time the user navigates to the page, or if you want to know when a user has navigated to a cached page, use the new pageshow event.

If you have behaviors that fire when a user navigates away from the page, but you want to take advantage of this new caching feature, and therefore don’t want to use the unload handler, use the new pagehide event.

pageshow event

This event works the same as the load event, except that it fires every time the page is loaded (whereas the load event doesn’t fire in Firefox 1.5 when the page is loaded from cache). The first time the page loads, the pageshow event fires just after the firing of the load event. The pageshow event uses a boolean property called persisted that is set to false on the initial load. It is set to true if it is not the initial load (in other words, it is set to true when the page is cached).

Set any JavaScript that you want to run every time a page loads to run when the pageshow event fires.

If you call JavaScript functions as part of the pageshow event, you can ensure these functions are called when the page is loaded in browsers other than Firefox 1.5 by calling the pageshow event as part of the load event, as shown in the sample later in this article.

pagehide event

If you want to define behavior that occurs the user navigates away from the page, but you don’t want to use the unload event (which would cause the page to not be cached), you can use the new pagehide event. Like pageshow, the pagehide event uses a boolean property called persisted. This property is set to false if the page is not cached by the browser and set to true if the page is cached by the browser. When this property is set to false, the unload handler, if present, fires immediately after the pagehide event.

Firefox 1.5 tries to simulate load events in the same order they would occur when the page is initially loaded. Frames are treated the same way as the top-level document. If the page contains frames, then when the cached page is loaded:

  • pageshow events from each frame fire before the pageshow event in the main document fires.
  • When the user navigates away from the cached page, the pagehide event from each frame fires before the pagehide event in the main document.
  • For navigation that occurs inside a single frame, events fire only in the affected frame.

Page caching despite unload and beforeunload handlers

If you want to use unload or beforeunload events and also preserve page caching, then you can simply remove these events in the event handler function and reinstate them in an pageshow handler function if you return to that page:

window.addEventListener('pageshow', PageShowHandler, false);
window.addEventListener('unload', UnloadHandler, false);

function PageShowHandler() {
	window.addEventListener('unload', UnloadHandler, false);
}

function UnloadHandler() {
	window.removeEventListener('unload', UnloadHandler, false);
}

Sample code

The sample below illustrates a page that uses both the load and pageshow events. This sample page behaves as follows:

  • In browsers other than Firefox 1.5, the following occurs each time the page loads: the load event triggers the onLoad function, which calls the onPageShow function (as well as an additional function).
  • In Firefox 1.5, the first time the page is loaded, the load event operates the same way as in other browsers. In addition, the pageshow event fires, and as persisted is set to false, no additional action occurs.
  • In Firefox 1.5, when the page is loaded from cache, only the pageshow event fires. As persisted is set to true, only the JavaScript actions in the onPageShow function are triggered.

In this example:

  • The page calculates and displays the current date and time each time the page is loaded. This calculation includes the seconds and milliseconds so you can easily test the functionality.
  • The cursor is placed in the Name field of the form the first time the page is loaded. In Firefox 1.5, when the user navigates back to the page, the cursor remains in the field it was when the user navigated away from the page. In other browsers, the cursor moves back to the Name field.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<head>
<title>Order query : Firefox 1.5 Example</title>
<style type="text/css">
body, p {
	font-family: Verdana, sans-serif;
	font-size: 12px;
   	}
</style>
<script type="text/javascript">
function onLoad() {
	loadOnlyFirst();
	onPageShow();
}

function onPageShow() {
//calculate current time
	var currentTime= new Date();
	var year=currentTime.getFullYear();
	var month=currentTime.getMonth()+1;
	var day=currentTime.getDate();
	var hour=currentTime.getHours();
	var min=currentTime.getMinutes();
	var sec=currentTime.getSeconds();
	var mil=currentTime.getMilliseconds();
	var displayTime = (month + "/" + day + "/" + year + " " + 
		hour + ":" + min + ":" + sec + ":" + mil);
	document.getElementById("timefield").value=displayTime;	
}

function loadOnlyFirst() {
	document.zipForm.name.focus();
}
</script>
</head>
<body onload="onLoad();" onpageshow="if (event.persisted) onPageShow();"> 
<h2>Order query</h2>

<form name="zipForm" action="http://www.example.com/formresult.html" method="get">
<label for="timefield">Date and time:</label>
<input type="text" id="timefield"><br>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="address">Email address:</label>
<input type="text" id="address"><br>
<label for="order">Order number:</label>
<input type="text" id="order"><br>
<input type="submit" name="submit" value="Submit Query"> 
</form>
</body>
</html>

In contrast, if the above page did not listen for the pageshow event and handled all calculations as part of the load event (and instead was coded as shown in the sample code fragment below), both the cursor position and date/time would be cached in Firefox 1.5 when the user navigated away from the page. When the user returned to the page, the cached date/time would display.

<script>
function onLoad() {
	loadOnlyFirst();

//calculate current time
	var currentTime= new Date();
	var year = currentTime.getFullYear();
	var month = currentTime.getMonth()+1;
	var day = currentTime.getDate();
	var hour=currentTime.getHours();
	var min=currentTime.getMinutes();
	var sec=currentTime.getSeconds();
	var mil=currentTime.getMilliseconds();
	var displayTime = (month + "/" + day + "/" + year + " " + 
		hour + ":" + min + ":" + sec + ":" + mil);
	document.getElementById("timefield").value=displayTime;
}

function loadOnlyFirst() {
	document.zipForm.name.focus();
}
</script>
</head>

<body onload="onLoad();">

Developing Firefox extensions

Firefox 1.5 extensions need to allow for this caching functionality. If you are developing a Firefox extension that you want to be compatible with both 1.5 and earlier versions, make sure that it listens for the load event for triggers that can be cached and listens for the pageshow event for triggers that shouldn’t be cached.

For instance, the Google Toolbar for Firefox should listen for the load event for the autolink function and to the pageshow event for the PageRank function in order to be compatible with both 1.5 and earlier versions.

{{ languages( { "it": "it/Usare_il_caching_di_Firefox_1.5", "de": "de/Benutzen_des_Zwischenspeichers_in_Firefox_1.5_(caching)", "fr": "fr/Utilisation_du_cache_de_Firefox_1.5", "ja": "ja/Using_Firefox_1.5_caching" } ) }}

Источник ревизии

<p>&nbsp;</p>
<h3 id="Introduction" name="Introduction">Введение</h3>
<p><a href="/en/Firefox_1.5_for_developers" title="en/Firefox_1.5_for_developers">Firefox 1.5</a> использует кэширование целых Web-страниц, включая их JavaScript-состояния, в рамках сессии браузера. Переходы по посещённым страницам вперёд-назад не требуют загрузки страниц, а JavaScript-состояния сохраняются. Эта функция, обозначаемая иногда как <strong>bfcache</strong> (Back-Forward Cache), делает навигацию по страницам очень быстрой. Такое кэшированное состояние сохраняется, пока пользователь не закроет браузер.</p>
<p>Есть случаи, в которых Firefox не кэширует страницы. Вот некоторые обычные программные причины того, что страница не кэширована:</p>
<ul>
  <li>страница использует обработчик <code>unload</code> или <code>beforeunload</code>;</li>
  <li>страница устанавливает заголовок «cache-control: no-store».</li>
  <li>доступ к сайту происходит по протоколу HTTPS, а страница устанавливает по меньшей мере один из следующих заголовков:
    <ul>
      <li>«Cache-Control: no-cache»</li>
      <li>«Pragma: no-cache»</li>
      <li>с заголовком «Expires: 0» or «Expires» со значением даты, лежащим в прошлом относительно значению заголовка «Date» (если только не указан также заголовок «Cache-Control: max-age=»);</li>
    </ul>
  </li>
  <li>страница не полностью загрузилась, когда пользователь ушёл с неё, или имеет прерванные сетевые запросы по другим причинам (например, <code>XMLHttpRequest</code>));</li>
  <li>страница имеет работающие IndexedDB-транзакции;</li>
  <li>страница верхнего уровня содержит фреймы (например, {{ HTMLElement("iframe") }}), которые не кэшируются по одной из перечисленных здесь причин;</li>
  <li>страница находится в фрейме и пользователь загружает новую страницу в этот фрейм (в этом случае, когда пользователь уходит со с этой страницы, последнее загруженное в фреймы содержимое есть то, что закэшировано).</li>
</ul>
<p>Эта новая функция кэширования меняет поведение загрузки страницы, так что Web-авторы могут захотеть:</p>
<ul>
  <li>узнать, когда на страницу происходит переход (когда она загружается из пользовательского кэша);</li>
  <li>определить поведение страницы, когда пользователь уходит со страницы (позволяя всё же странице быть закэшированной).</li>
</ul>
<p>Это позволяют сделать два новых события браузера.</p>
<h3 id="New_browser_events" name="New_browser_events">Новые события браузера</h3>
<p>Если вы используете эти новые события, ваши страницы продолжат правильно отображаться в других браузерах (мы протестировали старые версии Firefox, Internet Explorer, Opera и Safari), а при загрузке в Firefox 1.5 добавится новая функциональность кэширования.</p>
<p>Примечание: as of 10-2009 development versions of Safari added support for these new events (see <a class="link-https" href="https://bugs.webkit.org/show_bug.cgi?id=28758" title="https://bugs.webkit.org/show_bug.cgi?id=28758">the webkit bug</a>).</p>
<p>Standard behavior for Web pages is:</p>
<ol>
  <li>User navigates to a page.</li>
  <li>As the page loads, inline scripts run.</li>
  <li>Once the page is loaded, the <code>onload</code> handler fires.</li>
</ol>
<p>Some pages include a fourth step. If a page uses an <code>unload</code> or <code>beforeunload</code> handler, it fires when the user navigates away from the page. If an <code>unload</code> handler is present, the page will not be cached.</p>
<p>When a user navigates to a cached page, inline scripts and the <code>onload</code> handler do not run (steps 2 and 3), since in most cases, the effects of these scripts have been preserved.</p>
<p>If the page contains scripts or other behaviors that fire during loading that you want to continue to execute every time the user navigates to the page, or if you want to know when a user has navigated to a cached page, use the new <code>pageshow</code> event.</p>
<p>If you have behaviors that fire when a user navigates away from the page, but you want to take advantage of this new caching feature, and therefore don’t want to use the unload handler, use the new <code>pagehide</code> event.</p>
<h4 id="pageshow_event" name="pageshow_event">pageshow event</h4>
<p>This event works the same as the <code>load</code> event, except that it fires every time the page is loaded (whereas the <code>load</code> event doesn’t fire in Firefox 1.5 when the page is loaded from cache). The first time the page loads, the <code>pageshow</code> event fires just after the firing of the <code>load</code> event. The <code>pageshow</code> event uses a boolean property called <code>persisted</code> that is set to <code>false</code> on the initial load. It is set to <code>true</code> if it is not the initial load (in other words, it is set to true when the page is cached).</p>
<p>Set any JavaScript that you want to run every time a page loads to run when the <code>pageshow</code> event fires.</p>
<p>If you call JavaScript functions as part of the <code>pageshow</code> event, you can ensure these functions are called when the page is loaded in browsers other than Firefox 1.5 by calling the <code>pageshow</code> event as part of the <code>load</code> event, as shown in the sample later in this article.</p>
<h4 id="pagehide_event" name="pagehide_event">pagehide event</h4>
<p>If you want to define behavior that occurs the user navigates away from the page, but you don’t want to use the <code>unload</code> event (which would cause the page to not be cached), you can use the new <code>pagehide</code> event. Like <code>pageshow</code>, the <code>pagehide</code> event uses a boolean property called <code>persisted</code>. This property is set to <code>false</code> if the page is not cached by the browser and set to <code>true</code> if the page is cached by the browser. When this property is set to <code>false</code>, the <code>unload</code> handler, if present, fires immediately after the <code>pagehide</code> event.</p>
<p>Firefox 1.5 tries to simulate load events in the same order they would occur when the page is initially loaded. Frames are treated the same way as the top-level document. If the page contains frames, then when the cached page is loaded:</p>
<ul>
  <li><code>pageshow</code> events from each frame fire before the <code>pageshow</code> event in the main document fires.</li>
  <li>When the user navigates away from the cached page, the <code>pagehide</code> event from each frame fires before the <code>pagehide</code> event in the main document.</li>
  <li>For navigation that occurs inside a single frame, events fire only in the affected frame.</li>
</ul>
<h4 id="pagehide_event" name="pagehide_event">Page caching despite <code>unload</code> and <code>beforeunload</code> handlers</h4>
<p>If you want to use <code>unload</code> or <code>beforeunload</code> events and also preserve page caching, then you can simply remove these events in the event handler function and reinstate them in an <code>pageshow</code> handler function if you return to that page:</p>
<pre>
window.addEventListener('pageshow', PageShowHandler, false);
window.addEventListener('unload', UnloadHandler, false);

function PageShowHandler() {
	window.addEventListener('unload', UnloadHandler, false);
}

function UnloadHandler() {
	window.removeEventListener('unload', UnloadHandler, false);
}
</pre>
<h3 id="Sample_code">Sample code</h3>
<p>The sample below illustrates a page that uses both the <code>load</code> and <code>pageshow</code> events. This sample page behaves as follows:</p>
<ul>
  <li>In browsers other than Firefox 1.5, the following occurs each time the page loads: the <code>load</code> event triggers the <code>onLoad</code> function, which calls the <code>onPageShow</code> function (as well as an additional function).</li>
</ul>
<ul>
  <li>In Firefox 1.5, the first time the page is loaded, the <code>load</code> event operates the same way as in other browsers. In addition, the <code>pageshow</code> event fires, and as <code>persisted</code> is set to <code>false</code>, no additional action occurs.</li>
</ul>
<ul>
  <li>In Firefox 1.5, when the page is loaded from cache, only the <code>pageshow</code> event fires. As <code>persisted</code> is set to <code>true</code>, only the JavaScript actions in the <code>onPageShow</code> function are triggered.</li>
</ul>
<p>In this example:</p>
<ul>
  <li>The page calculates and displays the current date and time each time the page is loaded. This calculation includes the seconds and milliseconds so you can easily test the functionality.</li>
  <li>The cursor is placed in the Name field of the form the first time the page is loaded. In Firefox 1.5, when the user navigates back to the page, the cursor remains in the field it was when the user navigated away from the page. In other browsers, the cursor moves back to the Name field.</li>
</ul>
<pre>
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;HTML&gt;
&lt;head&gt;
&lt;title&gt;Order query&nbsp;: Firefox 1.5 Example&lt;/title&gt;
&lt;style type="text/css"&gt;
body, p {
	font-family: Verdana, sans-serif;
	font-size: 12px;
   	}
&lt;/style&gt;
&lt;script type="text/javascript"&gt;
function onLoad() {
	loadOnlyFirst();
	onPageShow();
}

function onPageShow() {
//calculate current time
	var currentTime= new Date();
	var year=currentTime.getFullYear();
	var month=currentTime.getMonth()+1;
	var day=currentTime.getDate();
	var hour=currentTime.getHours();
	var min=currentTime.getMinutes();
	var sec=currentTime.getSeconds();
	var mil=currentTime.getMilliseconds();
	var displayTime = (month + "/" + day + "/" + year + " " + 
		hour + ":" + min + ":" + sec + ":" + mil);
	document.getElementById("timefield").value=displayTime;	
}

function loadOnlyFirst() {
	document.zipForm.name.focus();
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="onLoad();" onpageshow="if (event.persisted) onPageShow();"&gt; 
&lt;h2&gt;Order query&lt;/h2&gt;

&lt;form name="zipForm" action="http://www.example.com/formresult.html" method="get"&gt;
&lt;label for="timefield"&gt;Date and time:&lt;/label&gt;
&lt;input type="text" id="timefield"&gt;&lt;br&gt;
&lt;label for="name"&gt;Name:&lt;/label&gt;
&lt;input type="text" id="name"&gt;&lt;br&gt;
&lt;label for="address"&gt;Email address:&lt;/label&gt;
&lt;input type="text" id="address"&gt;&lt;br&gt;
&lt;label for="order"&gt;Order number:&lt;/label&gt;
&lt;input type="text" id="order"&gt;&lt;br&gt;
&lt;input type="submit" name="submit" value="Submit Query"&gt; 
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In contrast, if the above page did not listen for the <code>pageshow</code> event and handled all calculations as part of the <code>load</code> event (and instead was coded as shown in the sample code fragment below), both the cursor position and date/time would be cached in Firefox 1.5 when the user navigated away from the page. When the user returned to the page, the cached date/time would display.</p>
<pre>
&lt;script&gt;
function onLoad() {
	loadOnlyFirst();

//calculate current time
	var currentTime= new Date();
	var year = currentTime.getFullYear();
	var month = currentTime.getMonth()+1;
	var day = currentTime.getDate();
	var hour=currentTime.getHours();
	var min=currentTime.getMinutes();
	var sec=currentTime.getSeconds();
	var mil=currentTime.getMilliseconds();
	var displayTime = (month + "/" + day + "/" + year + " " + 
		hour + ":" + min + ":" + sec + ":" + mil);
	document.getElementById("timefield").value=displayTime;
}

function loadOnlyFirst() {
	document.zipForm.name.focus();
}
&lt;/script&gt;
&lt;/head&gt;

&lt;body onload="onLoad();"&gt;
</pre>
<h3 id="Developing_Firefox_extensions" name="Developing_Firefox_extensions">Developing Firefox extensions</h3>
<p>Firefox 1.5 <a href="/en/Building_an_Extension" title="en/Building_an_Extension">extensions</a> need to allow for this caching functionality. If you are developing a Firefox extension that you want to be compatible with both 1.5 and earlier versions, make sure that it listens for the <code>load</code> event for triggers that can be cached and listens for the <code>pageshow</code> event for triggers that shouldn’t be cached.</p>
<p>For instance, the Google Toolbar for Firefox should listen for the <code>load</code> event for the autolink function and to the <code>pageshow</code> event for the PageRank function in order to be compatible with both 1.5 and earlier versions.</p>
<p>{{ languages( { "it": "it/Usare_il_caching_di_Firefox_1.5", "de": "de/Benutzen_des_Zwischenspeichers_in_Firefox_1.5_(caching)", "fr": "fr/Utilisation_du_cache_de_Firefox_1.5", "ja": "ja/Using_Firefox_1.5_caching" } ) }}</p>
Вернуть эту версию