2013-07-23 3 views
1

자바 스크립트를 최소화하기 위해 PHP 스크립트를 사용하고 있습니다. 문제는 서버가 응답하기 전에 스크립트가 자주 1 초 정도 걸리므로 목적을 거의 완전히 상실한다는 것입니다. 304를 보내는 것만으로도 여전히 일 때이 응답을 보내기 위해 잠시 시간이 걸리며 그 시간 동안 브라우저가 걸려 있습니다. 부하에PHP 스크립트를 사용하여 자바 스크립트를 축소하면 서버 응답 속도가 느려집니다.

,이 같은 스크립트 기능 :

  1. (쿼리 문자열 var에 null의 경우, 또는 사용 기본값) 쿼리 문자열 VAR에 따라
  2. 점검하십시오 경우로드시에 어떤 파일 (또는 파일)을 결정 파일의 캐시 된 사본을 사용할 수 있고 최신입니다 (서버에 저장된 .txt 파일입니다).
  3. 만약 그렇다면 아무것도하지 마십시오. 그렇지 않다면 캐시 파일이 생성되거나 다시 생성됩니다 (축소화를 위해 JShrink 0.5.1을 사용 중입니다)
  4. 마지막으로 캐시 파일의 etags 및 last-modified가 사용자의 내용과 일치하는지 확인하십시오
  5. - if 그래서, 단지 304
  6. 을 보낼 - 그것은 지속적으로이 작업을 수행하지 않습니다

캐시 파일에 ReadFile을하지 않을 경우 - 하나에 두 번째 걸릴 수 있습니다 새로 고침, 주변의 다음 번거야 두 가지 모두 304를 반환합니다. 일관성이 없기 때문에 지연은 하드 드라이브의 캐시 파일에 액세스하는 것입니다 (304를 전송할 때도 캐시 파일에 filemtime()을 수행해야하며 파일을 $ fileList에 저장하고 나중에 캐쉬 파일의 md5_file()을 사용하여 현재의 etag을 생성한다.

이 문제를 해결하는 방법에 대한 의견이 있으십니까?

<script type="text/javascript" src="/loadJS.php"></script> 
// steps 2 and 3 (check cache, update if necessary, fileList is an array of paths to .js files): 

if (file_exists($cacheFile)) { 
    $cacheLastModified = filemtime($cacheFile); 
    for($i = 0; $i < sizeof($fileList); $i++) { 
     /* check if any files in the list are newer than the cache's last modification date 
     * if so, cache must be updated 
     */ 
     if ($cacheLastModified < filemtime($fileList[$i])) { 
      $outdated = true; 
     } 
    } 
} 

if (isset($outdated) || !file_exists($cacheFile)) { 
    // update the cache file now 
    ob_start(); 
    foreach($fileList as $file) { 
     readfile($file); 
    } 
    $output = ob_get_clean(); 
    include("includes/JShrink-0.5.1.class.php"); 
    $output = Minifier::minify($output, array('flaggedComments' => false)); 

    if ($cacheFileFP = fopen($cacheFile, "w")) { 
     if (fwrite($cacheFileFP, $output)) { 
      fclose($cacheFileFP); 
     } else { 
      // handle fwrite errors 
     } 
    } else { 
     // handle fopen errors 
    } 
} 



// step 4 (function checks etags and modification date): 

function fileNotModified ($file) { 
    /* returns false if file NOT modified 
    * -- or an array of headers if file has been modified 
    * use two criteria to determine if file has been modified 
    * a) if-modified-since header vs the file's last-modified time 
    * b) etag match 
    * if if-modified-since is the same as file mod time, or etags match 
    * --- return array of headers to send 
    * else return false 
    * 
    * see http://stackoverflow.com/questions/2000715/answering-http-if-modified-since-and-http-if-none-match-in-php/2015665#2015665 
    */ 

    $gmtModifiedTime = gmdate('r', filemtime($file)); 
    $eTag = md5_file($file); 
    $result = false; 

    if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {   
     if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmtModifiedTime || str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == $eTag) { 
      $result["ETag"] = $eTag; 
      $result["Last-Modified"] = $gmtModifiedTime; 
     } 
    } 

    return $result; 
} 

// steps 5 and 6 (304 header or send readfile output): 

if ($headers = fileNotModified($cacheFile)) { 
    // send the headers and 304 not modified 
    foreach($headers as $name=>$value) { 
     header($name . ": " . $value); 
    } 
    header('HTTP/1.1 304 Not Modified'); 
    /*exit();*/ 
} else { 
    // read and output the cache 
    header("Last-Modified: " . gmdate("r", filemtime($cacheFile))); 
    header("Etag: " . md5_file($cacheFile)); 
    readfile($cacheFile); 
} 
+4

페이지가로드되면 js 소스 파일을 한 번만 압축 한 다음 축소 된 스크립트를 웹 서버에 업로드해야합니다. – Dave

+0

@Dave가 말한 것을 반영 할 수 있습니다. 이것은 PHP의 직업이 아닙니다. 웹 서버가 처리하도록하십시오. –

+0

@Dave이 조건 :'if (isset ($ outdated) || file_exists ($ cacheFile))'는 "모든 페이지로드시"로 축소되지 않는다고 말합니다. – Brewal

답변

0

나는 다음과 같은 코드를 테스트하지 못했지만, 이것은 당신이해야 할 일입니다 : 여기에 코드의 몇 가지 관련 블록은 당신이 모든에 작게를 할 필요가 없습니다

if(!file_exists($js_path_cache) || filemtime($js_path_cache) < filemtime($js_path) { 
    // MINIFY YOUR JS HERE 
} 
관련 문제