I'm trying to make a "slideshow" viewer for a number of books with chapters in them. The 开发者_运维百科"slides" are chunks of HTML data stored in a database. A chapter can consist of 50-100 slides, but they are quite small (1-2 kB each and pictures in some). I want the user to have buttons to click for the previous and next slide and minimise loading times.
What I have now is a PHP page called ContentFetcher.php that only queries the database to get the contents of one slide (section).
<?php
require_once 'Database.php';
echo Database::getInstance()->getSectionText($_GET["bookID"], $_GET["chapter"], $_GET["section"]);
?>
My Javascript runs a loop and fetches each section with $.get()
for the current chapter:
$(function() {
<? $db = Database::getInstance(); ?>
var chapterSize = <?= $db->getChapterSize($this->bookID, $this->chapter) ?>;
var chapterContent = []; // this is where I want to store the contents
var currentSection = <?=$this->section;?>;
for (var i = 1; i <= chapterSize; i++) {
$.get("ContentFetcher.php", {
bookID : <?= $this->bookID ?>,
chapter : <?= $this->chapter ?>,
section : i
}, function(data) {
chapterContent.push(data);
});
}
$("#slides").html(chapterContent[currentSection]); // show the current slide
});
So is this a good idea performance-wise? If so, my understanding of JS closures isn't that great yet - how can I access the same chapterContent
inside the closure?
This idea means you'll do between 50 and 100 HTTP requests to load one chapter ; and those will all be done almost at the same time.
So, each time someone tries to load a chapter, your webserver will get 100 requests in a couple of seconds -- might not be such a good idea.
In such a situation, I would probably try to implement something like this :
- When the user opens the chapter, do a single HTTP request, which will return the first 10 slides
- When the user arrives on slide 8, do a single HTTP request, to load the slides 11 to 20
- When the user arrives on slide 18, do a single HTTP request, to load the slides 21 to 30
- And so on
Of course :
- If a user arrives on slide 56 by typing its URL (if that's possible) or using some "goto slide X" feature, you must do an HTTP request to load slides 51 to 60.
- And it means users might have to wait for a little bit if they go from slide to slide too quick.
It will make both your client and server-side code a bit more complex, but it's probably one of the best solution :
- You won't load too much data at a time,
- You won't pre-load too much data,
- You you won't do too many HTTP requests,
- And those will be done a bit in advance, so the user doesn't have to wait to see new slides arrive.
No, this is definitely not a good idea. I'd recommend you just do one $.get() request to receive all the records in a JSON array.
Regarding closures, you must watch the excellent Douglas Crockfords' videos "The JavaScript Programming Language" (4 parts). Yes, the closures can be used this way, they are just great.
精彩评论