I'm trying to write a single-page web app in JavaScript. Desired behavior:
http://myapp.example.com
(the main page), or any other URL off of that domain for the first time, their browser downloads 1 large HTML file (and associated JS/CSS/image files, etc.). --> so big upfront download <div>
elements that each represent a different "page"; only 1 "page" div will be displayed at any given time I'm wondering how to do this. I'd greatly prefer something jQuery-based rather than trying to write something homegrown. But if I have to write this code myself, then given the following general structure of the 1 HTML file:
<html>
<head> ... </head>
<body>
<div id="home" class="page">
<!-- Content for home page, say http://myapp.example.com/#home. -->
</div>
<div id="about" class="page">
<!-- Content for About page, say http://myapp.example.com/#about. -->
</div>
<div id="contact" class="page">
<!-- Content for Contact page, say http://myapp.example.com/#contact. -->
</div>
<!-- Etc. for all other "pages" -->
</body>
</html>
How do I:
You can use and set the window.location.hash
and use that value to $("#yourDivId").show()
and $("#yourDivId").hide()
your divs.
On the onload
you can $("#yourDivId").show()
the requested (or default if none was requested) div, and $("#yourDivId").hide()
the other divs.
And on each link, either directly change the hash and set the requested div visible. Or set a timer that checks the hash on an interval to see if the hash has changed. (There is no native onhashchange event.)
I think you should hide every div at start.
$(div#page).hide();
Then, you can check the current URl by using:
var pathname = window.location.pathname;
Every time the user changes the URL: first hide every div, then check and show the desired div.
That is the reason of Single Page Application Framework's existence. I think it does worth learning some of the, such as AngularJS or BackboneJS.
If you want to abuse the browser history, I suggest you read this article on history.pushState()
. :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.