Javascript 如何检查css文件是否缩小或不使用php
我正在创建一个SEO分析器,它将检查CSS和js文件是否缩小。HTML解析器将从网站中提取CSS和js文件的URL 如何检查CSS/js文件是否使用PHP缩小 CSS文件的URL可以如下所示:Javascript 如何检查css文件是否缩小或不使用php,javascript,php,html,css,minify,Javascript,Php,Html,Css,Minify,我正在创建一个SEO分析器,它将检查CSS和js文件是否缩小。HTML解析器将从网站中提取CSS和js文件的URL 如何检查CSS/js文件是否使用PHP缩小 CSS文件的URL可以如下所示: http://fonts.googleapis.com/css?family=Dosis:200,300,400,500,600,700,800 http://www.inforge.in/css/style.css 试试这个: function is_mini($fileName){ $f = @
http://fonts.googleapis.com/css?family=Dosis:200,300,400,500,600,700,800
http://www.inforge.in/css/style.css
试试这个:
function is_mini($fileName){
$f = @fopen($fileName, 'r'); $l = strlen(file_get_contents($fileName));
if(strlen(fgets($f, $l)) === $l){
return true;
}
return false;
}
它根据
$fileName
打开一个文件进行读取,因此使用'r'
,然后根据fgets()
返回的单行测试文件的strlen()
。这是一个PHP函数,它可以通过网站解析并发现有多少本地CSS文件没有缩小。这比你要求的多了一点,但应该能帮你
<?php
/**
* Find the number of unminified CSS files on a website
* @param string $url The root URL of the website to test
* @param integer $lines_per_file What's the max number of lines a minified CSS file should have?
* @return integer Number of CSS files on a website that aren't minified
*/
function how_many_unminified_css_files( $url, $lines_per_file = 3 )
$unminimized_css_files = 0;
// Get the website's HTML
$html = file_get_contents( $url );
// Find all local css files
preg_match( "/({$url}.*\.css)/gi", $html, $css_files );
// Remove the global match that preg_match returns
array_shift( $css_files );
// Loop through all the local CSS files
// And count how many lines they have
foreach( $css_files as $css_file ) {
$linecount = 0;
// "Open" the CSS file
$handle = fopen($css_file, "r");
// Count the number of lines
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
// Close the CSS file
fclose($handle);
// If the CSS file has more lines than we deem appropriate,
// we'll consider it not minified
if ( $linecount > $lines_per_file ) {
$unminimized_css_files++;
}
}
// Return the number of files that we don't think are minified
return $unminimized_css_files;
}
您对“缩小”的定义是什么?当分析文件时,你认为什么是最小化的标准?由于没有正式的定义,这只能通过确定您的标准是什么,然后检查文件是否符合该标准来完成。这只是一个简单的想法。我会检查文件是否只有一行,以及是否会删除不必要的空格。此外,我会检查注释的存在。或者检查换行符与总文件大小的比率是否高于某个阈值?如果顶部有版权声明或其他注释,则缩小后的文件可能仍有多个换行符;如果多个库已捆绑到单个文件中,则即使文件缩小,它们也可能在新行上有各自的标题注释。ok。我为此编写代码。但正如@nnnnnn所提到的,即使是缩小的css和js文件也有空格和新行。缩小的代码没有标准。唯一正确的测试是(1)强制缩小文件副本并将其与源文件进行比较,或者(2)设置自己的缩小标准并对照CSS文件检查每个条件。如果你的网站在性能上受到了影响,那么你可能不想实时这么做。如果您正在尝试执行维护脚本,那么为什么不创建您自己的管理器/记录器并在第一次通过时缩小所有CSS?如果你正在创建自己的SEO分析器,我想建议是不要。可能已经有一个考虑了所有问题。你能告诉我背后的逻辑吗?你如何确定每个文件的行数值?