Можно ли кэшировать только часть (фон, панель навигации) веб-сайта вместо целого файла?

Я хочу кэшировать только элемент, потому что он используется на КАЖДОЙ моей веб-странице. Вот проверить это изображение. Это объясняется здесь. http://i.imgur.com/Qm7AVf9.png

-1

Решение

Не так, как вы думаете. Это будет кэширование на стороне сервера. Не на стороне клиента. Клиент кэширует только элементы страницы, такие как изображения, видео и т. Д. Они не кэшируют фактический HTML, если только сама страница не сообщает им, что он должен кэшироваться, и он не отличается от ранее кэшированной версии.

Так что в вашем примере кэшируются изображения во всех этих разделах, но не HTML. Лучшее, что вы можете сделать, это разбить разделы на собственные файлы и кэшировать их на стороне сервера.

Самый большой вопрос — почему вы их кешируете? Если вы хотите сэкономить на пропускной способности, вы, очевидно, не получите никакой помощи от кэширования на стороне сервера.

Вы можете добавить в свой файл .htaccess:

<FilesMatch "\.(js)$">
Header set Cache-Control "max-age=29030400, public"</FilesMatch>

<FilesMatch "\.(css)$">
Header set Cache-Control "max-age=7257600, public"</FilesMatch>

<FilesMatch "\.(jpg)$">
Header set Cache-Control "max-age=29030400, public"</FilesMatch>

<FilesMatch "\.(gif)$">
Header set Cache-Control "max-age=29030400, public"</FilesMatch>

<FilesMatch "\.(png)$">
Header set Cache-Control "max-age=29030400, public"</FilesMatch>

<FilesMatch "\.(mp4)$">
Header set Cache-Control "max-age=29030400, public"</FilesMatch>

<FilesMatch "\.(flv)$">
Header set Cache-Control "max-age=29030400, public"</FilesMatch>

Это позволит кэшировать все элементы на странице, которые могут быть кэшированы клиентом.

Если вы пытаетесь решить проблемы с нагрузкой на сервер, вы можете кэшировать разные части элементов, используя разные технологии. Например, Memcache может кэшировать ваши запросы MySQL, а затем использовать встроенный в PHP кэш Opcode, чтобы PHP не компилировался при каждом запуске файла. В этом случае было бы лучше разбить разделы на их собственные файлы и сделать так, чтобы они «включались» в индексную страницу.

Для кеширования MySQL с помощью Memcached вы можете обернуть свой код в запрос, чтобы увидеть, существует ли кеш, а затем в конце вашего кода сохранить результат MySQL для кеширования, чтобы запустить кеш. Это будет выглядеть примерно так:

// this little portion is standard if you have Memcache compiled into PHP.

$memcache_obj = new Memcache;
$memcache_obj->connect('127.0.0.1', 11211);

// We try to load the memcache result if it exists
$profile = $memcache_obj->get("YouPickThisNameOnYourOwn");

// Did it exist? If NOT get it from MySQL
if (!is_array($profile)) {

$mysqli = new MySQLi("localhost", "MYSQL_UserName","MYSQL_Password","MYSQL_Database");
$sqlquery = $mysqli->query("SELECT whatever you are selecting");

// Run through and make the array you want normally...
for ($x=0;$x < $sqlquery->num_rows;$x++) {
$rowprofiles = $sqlquery->fetch_assoc();

// Here I am creating an array with the results and I had selected id, text_description, subdir, crc, url from MYSQL
$profile[$x] = array ("id" => $rowprofiles['id'], "text" => $rowprofiles['text_description'], "pic" => "http://www.domain.com/{$rowprofiles["subdir"]}/{$rowprofiles["crc"]}.jpg", "url" => $rowprofiles['url']);
}
// freeing up $sqlquery resource
$sqlquery->free();

// Here I am saving the result of the query as an associative array into memcache with a short time limite of 300 seconds. You might want longer for non changing data
$memcache_obj->add('YouPickThisNameOnYourOwn', $profile, false, 300);

// if I ended up using a query instead of memcache, close out the connection
if (isset($mysqli)) { $mysqli->close(); }
}

// end if the if... had it been memcache'd the script would bypass the query and just come here with the array and spit it out
foreach ($profile as $piece) {
echo '<div class="gallery"><img  src="'.$piece['pic'].'" alt="'.$piece['text'].'"  width="300" height="225"  border="1" /></div>';
echo '<div class="gallery">'.substr($piece['text'],0,192).'</div>';
}

// hope this helps!
// You can run a file with just <? phpinfo(); ?> inside it to see if your host already has memcache compiled into your PHP installation.
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector