2012年7月5日 星期四

jQuery Mobile : 關於 data-prefetch (1)

jQuery Mobile網頁預先載入功能可以減少使用者等待網頁載入時間。下面程式展示在jQuery Mobile中從 myPage1.html (內含Page1)要載入myPage2.html(內含Page2)顯示。

myPage1.html完整CODE

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="Scripts/jquery.mobile-1.1.0.css" rel="stylesheet" type="text/css" />
  <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
  <script src="Scripts/jquery.mobile-1.1.0.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(document).on('pageinit', '#Page1', function (event) {
      alert('myPage1 init');
    });
    $(document).on('pageinit', '#Page2', function (event) {
      alert('myPage2 init');
    });
  </script>
</head>
<body>
  <div data-role="page" id="Page1">
    <div data-role="header" data-position="fixed">
      <h1>myPage1</h1>
    </div>
    <div data-role="content">
      <a href="myPage2.html" >Goto Page2</a>
    </div>
    <div data-role="footer" data-position="fixed">
      <h1>@Copyright 米米貓</h1>
    </div>
  </div>
</body>
</html>

myPage2.html完整CODE

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="Scripts/jquery.mobile-1.1.0.css" rel="stylesheet" type="text/css" />
  <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
  <script src="Scripts/jquery.mobile-1.1.0.js" type="text/javascript"></script>
</head>
<body>
  <div data-role="page" id="Page2" data-position="fixed">
    <div data-role="header">
      <h1>myPage2</h1>
    </div>
    <div data-role="content">
      <p>Page2</p>
    </div>
    <div data-role="footer" data-position="fixed">
      <h1>@Copyright 米米貓</h1>
    </div>
  </div>
</body>
</html>

特別要注意的是雖然Page2存在於myPage2.html,但事件的程式碼還是寫在myPage1.html,這是因jQuery Mobile載入其他網頁時會忽略被載入的網頁<head>中的javascript。

myPage1.html 使用了以下超連結連接到myPage2:
 

<a href="myPage2.html" >Goto Page2</a>

在 myPage1.html 註冊Page1與Page2的pageinit事件,此事件在Page載入時觸發,:

<script type="text/javascript">
    $(document).on('pageinit', '#Page1', function (event) {
      alert('myPage1 init');
    });
    $(document).on('pageinit', '#Page2', function (event) {
      alert('myPage2 init');
    });
  </script>

從瀏覽器測試 myPage1.htm,執行時會先跳出myPage1初始化了:

image

接著若使用者點選 Go to Page2

image

myPage2在此時才初始化

image

然後就可以看到myPage2

image

若修改 myPage1.html 超連結,使用網頁預載功能 : data-prefetch="true"

<a href="myPage2.html" data-prefetch="true">Goto Page2</a>

執行順序,先myPage1 init:

image

接著是 myPage2 init, 在此階段已先載入myPage2.html

image

然後才出現myPage1

image

沒有留言:

總網頁瀏覽量