2012-08-05 69 views
5

我目前正在嘗試綁定我的JavaScript,因此我可以在頁面速度/ yslow中獲得更高的分數。但是我用這種方法遇到了牆壁。我目前使用這個TUTORIAL作爲捆綁js文件的指導。我打電話給js文件,但在firefox工具顯示文件bundle.js不存在這是真實的,但與htaccess我將文件從bundle.php鏈接到bundle.js。但我沒有得到任何結果。有人可以幫我指出問題,還是有更好的方法來捆綁js文件?用htaccess和php綁定javascript

這是我的EXAMPLE。當正常使用js文件時,它應該顯示4個用於文件上傳的輸入字段。

這是我如何調用JS文件

<script src='core/bundle.js?js=js/jquery-ui-1.8rc2.custom.min.js,js/globalFunctions.js,js/uploaderPreviewer.js,js/itemForm.js&amp;m=4948599067'> 
</script> 

.htacces更改文件類型*

RewriteEngine on 
RewriteRule ^bundle.js$ bundle.php [QSA,L] 

核心/ bundle.php

include "JSMin.php"; 
$path = "../../"; 
$files = explode(",", $_GET['js']); 
$missing = array(); 

$cache = ''; 
foreach ($files as $index => $file) { 
    if (strtolower(substr($file, -2)) != 'js') { 
     unset($files[$index]); 
    } else if (file_exists($path.$file)) { 
     $cache .= $file; 
     $cache .= filemtime($path.$file); 
    } else { 
     $missing[] = $file; 
     unset($files[$index]); 
    } 
} 

$cache = 'cache/'.md5($cache); 

if (count($missing)) { 
    header("Content-type: text/javascript"); 
    header("Pragma: no-cache"); 
    header("Cache-Control: no-cache"); 
    echo "alert('Could not load the following javascript source files:\\n\\n- ".implode("\\n- ", $missing)."\\n\\nJavascript not loaded/running!');"; 
    exit; 
} 

if (count($files)) { 
    // create cached version if not present 
    if (!file_exists($cache)) { 
     $js = ''; 
     foreach ($files as $file) { 
      $js .= JSMin::minify(file_get_contents($path.$file)); 
     } 

     file_put_contents($cache, $js); 
    } 

    // calculate last-modified & etag send caching headers 
    $last_modified_time = filemtime($cache); 
    $etag = md5_file($cache); 

    header("Content-type: text/javascript"); 
    header("Pragma: public"); 
    header("Cache-Control: public"); 
    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
    header("Etag: ".$etag); 

    if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { 
     header("HTTP/1.1 304 Not Modified"); 
     exit; 
    } 

    readfile($cache); 
} 
+0

你可以試試core/bundle.js的core/bundle.php文件嗎?如果它有效,那麼.htaccess可能有問題。 – 2012-08-05 22:25:38

+0

如果提到'if(strtolower(substr($ file,-2))!='js'){'是易受攻擊的代碼,那就太好了。例如:'.htpasswd%00js'其中'%00'是一個空字節,將通過您的條件,並且它將被操作系統解釋爲'.htpasswd'。有關更多信息,請參閱[this](https://www.owasp.org/index.php/File_System#Path_traversal)和[that](https://www.owasp.org/index.php/Path_Traversal)。 – HoLyVieR 2012-08-05 23:22:32

+0

你可以加載php爲js,而不是調用bundle.js,只需簡單地把