Если вы хотите избежать загрузки данных в случае клиента с включенным JS, вам может потребоваться объединить методы на стороне сервера и на стороне клиента.
Это можно использовать в качестве приблизительного руководства. Раскрытие информации - Я не проверял ничего из этого!
Например, если структура вашего сайта выглядит следующим образом:
/
page1.jsp
fragment1_1.jsp
fragment1_2.jsp
page2.jsp
fragment2_1.jsp
fragment2_2.jsp
...
Тогда page1.jsp может выглядеть такэто (извините, если вы не знаете JSP и jQuery, но в любом случае это в основном псевдокод):
<%!
// Define a method to help us import fragments into the current page.
// Conditional import of fragment based on isJSEnabled
void myImport (String fragment, boolean isJSEnabled, HttpServletResponse res) {
if (!isJSEnabled) {
// output fragment contents directly to response
String contents = // get contents of fragment
res.getWriter().write(contents);
}
}
%>
<%
// How to work out if JS is enabled on the server-side?
// Not sure it can be done. So need to be told by the browser somehow.
// Maybe a request parameter. So if param not present, assume no JS.
boolean isJSEnabled = (null != req.getParameter("js"));
%>
<html>
<head>
<script>
// Try and redirect to JS version of page as soon as possible,
// if we're not already using the JS version of the page.
// This code does not take into account any existing request parameters for
// the sake of brevity.
// A browser with JS-enabled that was incrementally downloading and parsing
// the page would go to the new URL.
if (window.location.href.indexOf("js=true") < 0) {
window.location.href += "?js=true";
}
</script>
</head>
<body>
<h1 class="fragment_header" data-fragment-id="fragment1_1">Fragment 1</h1>
<div>
<%
// Conditionally import "fragment1_1".
myImport("fragment1_1", isJSEnabled);
%>
</div>
<h1 class="fragment_header" data-fragment-id="fragment1_2">Fragment 2</h1>
<div>
<%
// Conditionally import "fragment1_2".
myImport("fragment1_2", isJSEnabled);
%>
</div>
<script>
// For each fragment header, we attach a click handler that loads the
// appropriate content for that header.
$(".fragment_header").click(function (evt) {
var header = $(evt.target);
// Find the div following the header.
var div = header.next("div");
if (div.children().length < 1) {
// Only load content if there is nothing already there.
div.load(header.attr("data-fragment-id") + ".jsp");
}
});
$("a").click(function (evt) {
// Stop the browser handling the link normally.
evt.preventDefault();
// Rudimentary way of trying to ensure that links clicked use the
// js=true parameter to keep us is JS mode.
var href = anchor.attr("href");
var isLocalHref = // logic to determine if link is local and should be JS-ified.
if (isLocalHref) {
href = href + "?js=true";
}
window.location.href = href;
});
</script>
</body>
</html>
Пользователь, просматривающий page1.jsp, изначально получит статическую версию, хотя JS включенбраузер переключится на версию с поддержкой JS как можно скорее.
Поскольку мы прикрепляем обработчики кликов ко всем ссылкам, мы можем контролировать загрузку следующей страницы.Если JS отключен в какой-то момент, параметр js = true не будет добавлен к каждому href
, и пользователь вернется к статической странице.