jQuery MobileでAjaxで取得したページでスタイルシートを反映させる
リクリのセミナーでjQuery MobileでAjaxで取得したページのスタイルシートが反映されないとの質問を受けました。
イメージとしてはこんな感じだと思います。
index1.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
<title>jQuery Mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<section id="page1" data-role="page">
<header>
<h1>page1</h1>
</header>
<a href="index2.html">page2</a>
</section>
</body>
</html>
style1.css
#page1{
background:blue;
}
index2.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
<title>jQuery Mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
<link rel="stylesheet" href="style2.css">
</head>
<body>
<section id="page2" data-role="page">
<header>
<h1>page2</h1>
</header>
<a href="index1.html">page1</a>
</section>
</body>
</html>
style2.css
#page2{
background:blue;
}
こういった構成の場合、index2.htmlが表示された際にstyle2.cssの内容が反映されません。
これはjQuery MobileではデフォルトのAjaxを利用したページ遷移では、遷移先のHTML(index2.html)からdata-role属性「page」がついた箇所のみをAjaxで取得し、遷移元のHTML(index1.html)内に挿入して表示します。そのため、index2.html内のlink要素はページ内に反映されません。
対応として、少し邪道ですがlink要素をページ要素内に記述することでページ読み込み時にスタイルシートも読み込むことが可能になります。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
<title>jQuery Mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
</head>
<body>
<section id="page2" data-role="page">
<link rel="stylesheet" href="style2.css">
<header>
<h1>page2</h1>
</header>
<a href="index1.html">page1</a>
</section>
</body>
</html>
ただ、jQuery Mobileを利用する場合は、全てのHTMLファイルが遷移元になる可能性を想定しないとだめでしょう。上記の例ではindex2.htmlをランディング ページと想定した場合index1.htmlでlink要素で指定しているスタイルシート(style1.css)が読み込まれません。
jQuery Mobileで利用するスタイルシートは全てのページで読み込んでおくのが間違いがない方法です。
<link rel="stylesheet" href="style1.css">
<link rel="stylesheet" href="style2.css">
サンプル(index1.html) / サンプル(index2.html)
スポンサードリンク
«第6回リクリセミナー『スマートフォン向けサイト制作の「これから」を考える』が終了しました | メイン | background-sizeとグラデーション»