GithubHelp home page GithubHelp logo

rmrevin / yii2-minify-view Goto Github PK

View Code? Open in Web Editor NEW
191.0 14.0 67.0 224 KB

Yii2 View component with minification css & js

License: MIT License

PHP 96.45% CSS 2.48% JavaScript 1.07%
yii php minify minification view

yii2-minify-view's Introduction

Yii 2 Minify View Component

The main feature of this component - concatenate and compress files connected through "AssetBundle".

License Latest Stable Version Latest Unstable Version Total Downloads

Code Status

Scrutinizer Code Quality Code Coverage Travis CI Build Status Dependency Status

Support

GutHub issues or public chat.

Installation

The preferred way to install this extension is through composer.

Either run

composer require rmrevin/yii2-minify-view

or add

"rmrevin/yii2-minify-view": "^1.15",

to the require section of your composer.json file.

Configure

<?php

return [
	// ...
	'components' => [
		// ...
		'view' => [
			'class' => '\rmrevin\yii\minify\View',
			'enableMinify' => !YII_DEBUG,
			'concatCss' => true, // concatenate css
			'minifyCss' => true, // minificate css
			'concatJs' => true, // concatenate js
			'minifyJs' => true, // minificate js
			'minifyOutput' => true, // minificate result html page
			'webPath' => '@web', // path alias to web base
			'basePath' => '@webroot', // path alias to web base
			'minifyPath' => '@webroot/minify', // path alias to save minify result
			'jsPosition' => [ \yii\web\View::POS_END ], // positions of js files to be minified
			'forceCharset' => 'UTF-8', // charset forcibly assign, otherwise will use all of the files found charset
			'expandImports' => true, // whether to change @import on content
			'compressOptions' => ['extra' => true], // options for compress
			'excludeFiles' => [
            	'jquery.js', // exclude this file from minification
            	'app-[^.].js', // you may use regexp
            ],
            'excludeBundles' => [
            	\app\helloworld\AssetBundle::class, // exclude this bundle from minification
            ],
		]
	]
];

yii2-minify-view's People

Contributors

acerix avatar aleksei-s-popov avatar darcoder avatar renatocassino avatar rmrevin avatar sadovojav avatar synacksa avatar vicvicos avatar zayec77 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-minify-view's Issues

Fixing Render Blocking Javascript and CSS in the Above-the-fold content

Hi
Thanks.
I want to solve this problem by putting the following code:

<script type="text/javascript"> function downloadJSAtOnload() { var element = document.createElement("script"); element.src = "defer.js"; document.body.appendChild(element); } if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; </script>

How do I get the name of the compressed Js file and put this code in page?

Performance - compress_output

I’d like to just suggest, that in docs could be written information that turning the compress_output directive on can have significant performance impact.

40-50 ms on medium page. More html, bigger impact every visit, because there isn’t any caching.

The main point is, that if you use gzip compression on you server (which people usually does), there is no other size reduction at all (less then kB). So I’d recommend to turn this directive off on default and mention it in docs with the reasons.

Need to check a file existence

File: components\CSS.php (line:53)

$content = file_get_contents($file);

Need to check a file existence and if it not exist generate exception, if site mode is production you will get unknown error #2. It was very hard to find the cause of the error.

Determining minification

@rmrevin I want to know how it determines to re-minify all the files again. As it is re-minifying my asset bundles on random requests. Which has same asset bundles? What will happen when there is no change in assets. Will it going to minify them again? Does it use timestamp with files?

Compress Inline code

Is it possible to add inline scripts compression and packaging them in a file?

No such file in css

Hello, I have a problem with CSS import.
When I have import like this:

@import url("animate.min.css");
it cause exception:

file_get_contents(/css/alpha.css): failed to open stream: No such file or director

Option to avoid minify <pre> at all

I have site which use a lot of "pre" elements and i do new lines by myself. Your minify add one more new line at the end, cause you don't use PHP_EOL and just put "\n", so now i have 2 new lines instead of just 1.

Broken external file support

Currently, external files weren't be ignored by the $schema array from line 43.
In my case the process failes on line 122: $content = file_get_contents(\Yii::getAlias($this->base_path) . $file); while trying to include an external file using // shema in asset:
file_get_contents(/var/www/[..]/dev/web///fonts.googleapis.com/css?family=Exo+2:400,600,800): failed to open stream: No such file or directory

when in localhost not conected to intenet bad error

PHP Warning – yii\base\ErrorException
file_get_contents(): php_network_getaddresses: getaddrinfo failed: No such host is known.
in C:\xampp\htdocs\zoop\vendor\rmrevin\yii2-minify-view\components\CSS.php at line 279

I got this error when i was not connect to internet that's min when a file on a server that have problem
my site with this ext not working when it dosent cash the content of that css or js file !!

plz change code when can not get a file dont try to minify that file

option parameter : minify js+css / only js / only css

I'm new to github, so forgive if my request is in wrong category.

Great extensions but minifying css causing conflicts in my case. Could you add parameter to decide if i want to minify js&css or just separate files?

For now i've just commented out #102 line of View.php and it's working good but want to have that solution updateable.

It will be great. Thank You.

Missing newlines in textareas when "compress_output" = true

Hi,

not sure if it is my fault or if something going wrong with the extension, but when I'm enabling the compress_output option I have a huge problem with all of my textareas.

My View:

<div class="col-xxs-12"><?= $form->field($studio, 'studioAddress')->textArea()->label( PhobUtils::t('Address') ) ?></div>

My config:

'view' => [
            'class' => '\rmrevin\yii\minify\View',
            'enableMinify' => !YII_DEBUG,
            'web_path' => '@web', // path alias to web base
            'base_path' => '@webroot', // path alias to web base
            'minify_path' => '@webroot/minify', // path alias to save minify result
            'js_position' => [ \yii\web\View::POS_END ], // positions of js files to be minified
            'force_charset' => 'UTF-8', // charset forcibly assign, otherwise will use all of the files found charset
            'expand_imports' => true, // whether to change @import on content
            'compress_output' => true, // compress result html page
        ]

Output with compress_output=true:
issue-false

My config:

'view' => [
            'class' => '\rmrevin\yii\minify\View',
            'enableMinify' => !YII_DEBUG,
            'web_path' => '@web', // path alias to web base
            'base_path' => '@webroot', // path alias to web base
            'minify_path' => '@webroot/minify', // path alias to save minify result
            'js_position' => [ \yii\web\View::POS_END ], // positions of js files to be minified
            'force_charset' => 'UTF-8', // charset forcibly assign, otherwise will use all of the files found charset
            'expand_imports' => true, // whether to change @import on content
            'compress_output' => false, // compress result html page
        ]

Output with compress_output=false:
issue-true

Did I something wrong or is this a bug?

Cheers & THX 😉

minify breaks pjax widget

yii2-minify-view appears to break pjax widgets when minifyCss is enabled. The pjax loading functionality appears to get completely disabled.

Missed .gitignore in folder

Git status after adding extension.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   composer.json
        modified:   composer.lock
        modified:   frontend/config/main.php
        new file:   frontend/web/minify/2068bd333df95e0693e6d53c513f4bde2fd06390.js
        new file:   frontend/web/minify/3bbef2fa2d1790f3eecdfcd429535a39990f5e76.css
        new file:   frontend/web/minify/a4f923bee4b1b84096b334981a6f4a3523916862.js
        new file:   frontend/web/minify/a67604cb503b0c1b5a21eb71bcec724b091cf55c.js

I think extension should add this file automatically after creating minify folder /frontend/web/minify/.gitignore.

Error with relative import in css file

Hi,
When minifying with iCheck css on my Asset (such as:

public $css = [
        'themes/adminlte/plugins/iCheck/all.css',
..];

I get that error:
file_get_contents(.../web/web/themes/adminlte/plugins/iCheck/minimal/_all.css): failed to open stream: No such file or directory

When I open all.css file, I found that line at the very first:

/* iCheck plugin skins
----------------------------------- */
@import url("minimal/_all.css");

invalid asset file path

PHP Warning – yii\base\ErrorException

sha1_file(/home/wordcoun/public_html/new/advanced/frontend/web/new/advanced/frontend/web/assets/8604a1d6/css/bootstrap.css): failed to open stream: No such file or directory

It's duplicating the /new/advanced/frontend/web/ part of the path

cut conditions in $jsOptions

For example
I create AssetBundle for include js files in HEAD section for IE :

<?php
namespace app\components;
use Yii;

use yii\web\AssetBundle;

class IEAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'bookcard/js/html5shiv.js',
        'bookcard/js/selectivizr-min.js',
    ];

    public $jsOptions = ['condition' => 'lte IE9', 'position' =>  \yii\web\View::POS_HEAD];
}

in my main Bundle I write

    public $depends = [
        'app\components\IEAsset',
        'yii\web\YiiAsset', // yii.js, jquery.js
    ];

And I get the following result

    <link href="/minify/dbac1fa8cc7c4a476dd3451eeb1f3f974a58e21a.css" rel="stylesheet">
<script src="/bookcard/js/html5shiv.js"></script>
<script src="/bookcard/js/selectivizr-min.js"></script>

If disable minify

<!--[if lte IE9]>
<script src="/bookcard/js/html5shiv.js"></script>
<![endif]-->
<!--[if lte IE9]>
<script src="/bookcard/js/selectivizr-min.js"></script>
<![endif]-->

Empty file and bad links

In my @app/web folder there is new folder called minify and there is empty .css file (only @charset "UTF-8";).

Also, script generates bad links
<link href="/minify/da39a3ee5e6b4b0d3255bfef95601890afd80709.css" rel="stylesheet">
but it should be something like this
<link href="my_app_name/minify/da39a3ee5e6b4b0d3255bfef95601890afd80709.css" rel="stylesheet">

I use default configuration.

composer install

I'm using the advanced extended template where all sources are held in _protected and therefore the vendor folder is _protected/vendor.

Your composer definition is trying to install into just /vendor and is therefore not accessible to any of the source code.

Is this due to the Type: yii2-extension
rather than type: library that most other extensions seem to use?

excludeBundles doesn't work

Using your plugin i found that another extension, Dosamigos/Leaflet, doesn't work properly (leaflet.js has a bug that came out only when itd minified).
I tried to exclude the bundle asset but it doesn't work. I do it like this in the config file:

'excludeBundles' => [ \dosamigos\leaflet\LeafLetAsset::class, ],

Am i using it wrong?

External sources

How can we handle external sources? Like jQuery with its //code.jquery.com/jquery-1.11.2.min.js or smth else.

Google: Eliminate render-blocking JavaScript and CSS in above-the-fold content

It is possible to leave the CSS in the <style> tag, instead of the file?

Error PageSpeed Insights
None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

Some interesting features that you could implement.
https://github.com/skeeks-semenov/yii2-assets-auto-compress

CSS hashing problem

I have some issue with the latest version (1.7.6)

When I modify a css file and then I reload the page, I got the same hash for the css files, like before the modification. Thats why the minified css will not overwritten, and the style is not refresh. And only 1 minified .css and .js files exist in the minified folder.

When I checkout to 1.7.3 it works. And on 1.7.4 if i modify the

public $schemas = ['//', 'http://', 'https://', 'ftp://'];

line to

public $schemas = ['/', 'http://', 'https://', 'ftp://'];

it works too.

The further changes was too complex, but something went wrong. Don't you realized this issue yet? Can you look after it? Thanks!

excludeBundle error - Array to string conversion

Trying to use excludeBundles property, but when the css item is in array format, it runs into exception error 'Array to string conversion'.
eg:

$css = [
    ['style.css', 'id' => 'myStyle'],
];

In 1.15.1, error is in MinifyComponent.php line 105.
I just realized there's V2, tested with this version and the error is in MinifyComponent.php line 112.

AJAX / Duplicated CSS file

I have a page where some parts of the content is fetched via AJAX.
When all assets are minified, the ajax content includes link to a css file which has already been included in the minified file. This is causing an issue if there are customized style defined for a specific class, and that is overwritten by this css file.

Eg, the ajax content displays bootstrap Progress widget which requires bootstrap.css. This css file has already been minified. In the html output for the ajax section there's additional html <link href="/minify/(random string).css" rel="stylesheet">.

If concatCSS property is set to false, this line does NOT appear in the output and the page is displayed as intended. It seems somehow the ajax page knows that the file has already been included in the main page. Can this be fixed when concatCss property is set to true? Or is there a workaround solution not to minify asset files?

Path incorrect in Advanced Template

I use advanced application template with separate in backend and frontend, but give error file_get_contents(C:\xampp\htdocs\dashboard/backend/web/dashboard/admin/assets/3b75345a/css/bootstrap.css): failed to open stream: No such file or directory

'view' => [
            'class' => '\rmrevin\yii\minify\View',
            'enableMinify' => true,
            'base_path' => '@backend/web', // path alias to web base
            'minify_path' => '@backend/web/minify', // path alias to save minify result
            'js_position' => [ \yii\web\View::POS_END ], // positions of js files to be minified
            'force_charset' => 'UTF-8', // charset forcibly assign, otherwise will use all of the files found charset
            'expand_imports' => true, // whether to change @import on content
        ]

I use @app/web or @web still give the wrong output path

When there is no css files to minify

Thanks for this plugin.
In components/CSS.php file line 28 function minify,
When there is no file to minify foreach returns "Invalid argument supplied for foreach()"
Correct me if i'm wrong, I think there should be "if(!empty($cssFiles))".

plz update your repo

Hi in php 7.1.13 I see a error in your repo dependency "mrclay/minify". error is in "CSSmin" class in this method:
private function normalize_int($size)
{
if (is_string($size)) {
switch (substr($size, -1)) {
case 'M': case 'm': return $size * 1048576;
case 'K': case 'k': return $size * 1024;
case 'G': case 'g': return $size * 1073741824;
}
}

    return (int) $size;
}

it is because $size has "M" suffix like "300M" and in new php version it can not multiple, but work in older php version.

I found that mrclay/minify have new version 3 and i suggest you to update your repo for compatibility with this new version.

Google Recaptcha does not load using yii2-minify-view

Hi rmrevin,

at first: thanks a lot for your wonderful extension. It is great !

unfortunately i stumbled upon a problem:

I use the https://github.com/himiklab/yii2-recaptcha-widget to display an captcha on my page.

This widget loads a .js file directly from google:
https://github.com/himiklab/yii2-recaptcha-widget/blob/master/ReCaptcha.php#L109

When activating your extension, the .js file stops being loaded ! I have no Idea why this happens.
This is my configuration - which is very standard:

[
            'class' => '\rmrevin\yii\minify\View',
            'enableMinify' => true,
            'concatCss' => true,
            'minifyCss' => true,
            'concatJs' => true,
            'minifyJs' => true,
            'minifyOutput' => true,
            'webPath' => '@web',
            'basePath' => '@webroot',
            'minifyPath' => '@webroot/minify',
            'jsPosition' => [\yii\web\View::POS_END],
            'forceCharset' => 'UTF-8',
            'expandImports' => true,
            'compressOptions' => ['extra' => true],
        ],

There is no AssetBundle to ignore since the file gets loaded from google. I also tried to do this:

  'excludeFiles' => [
                '//www.google.com/recaptcha/api.js?hl=de&render=explicit&onload=recaptchaOnloadCallback',
          
            ],

but without success.

Do you have any ideas ?

Thanks a lot in advance !

compressed on each pageload?

Thanks for a great component!

Just have a question re: its operation - are the files compressed on each pageload? (worried about page load time if this is the case...)

I'm comparing this component vs using something like grunt to create .min.js files then adding these to source control and pointing to on PROD env (this way min files generated once only).

thanks
gvanto

Duplicating js

Hi,

I have an AssetBundle (AB) on Head position (3 css and 1 js) and another one on End position (0 css and 15 js) in certain page. Whe using this extension, all the js files from both AB are mixed up in only one file and placed in the both html positions. I mean that in Head i have 1 file minified (1 + 15 = 16 js) and in the End i have the same file.

What should be the result?
One js file in the head with just 1 minified js file and a different file in the end with 15 minified js files.

My relevant config:

'js_position' => [\yii\web\View::POS_HEAD, \yii\web\View::POS_END], // positions of js files to be minified

My relevant resulting html:

<head>
...
<script src="/clientes/sg2/public_html/frontend/web/minify/da39a3ee5e6b4b0d3255bfef95601890afd80709.js">
...
</head>
<body>
.....
....
<script src="/clientes/sg2/public_html/frontend/web/minify/da39a3ee5e6b4b0d3255bfef95601890afd80709.js">
</body>
...

What is wrong? And what could I do to help?

Place minify files on s3 bucket

Is there any way by which we can directly place our minify files on s3 bucket and use the cdn url of those menify files ?

Pjax does not work with the current configuration.

Hello!

Pjax does not work with the current configuration. It is used for adding comments to the site, so the first time it is added without reloading, and the second time it reloads the page. This happens if the 'concatJs' parameter is true.

Please help solve this problem. I've already broken my head.. there are no errors in the console, but the page is reloaded if you try to use the form a second time (in one session). There is no redirect on the server side, the comment is added successfully but with a reboot.

I apologize for my English.

`<?php
'view' => [
'class' => '\rmrevin\yii\minify\View',
'enableMinify' => !YII_DEBUG,
// 'enableMinify' => YII_DEBUG,
'concatCss' => true, // concatenate css
'minifyCss' => true, // minificate css
'concatJs' => true, // concatenate js - if 'false' - Pjax worked.
'minifyJs' => true, // minificate js
'minifyOutput' => true, // minificate result html page
'webPath' => '@web', // path alias to web base
'basePath' => '@webroot', // path alias to web base
'minifyPath' => '@webroot/source', // path alias to save minify result
'jsPosition' => [
\yii\web\View::POS_END,
], // positions of js files to be minified
'forceCharset' => 'UTF-8', // charset forcibly assign, otherwise will use all of the files found charset
'expandImports' => true, // whether to change @import on content
'compressOptions' => ['extra' => true], // options for compress
'excludeFiles' => [
// 'jquery.js', // exclude this file from minification
// 'app-[^.].js', // you may use regexp
],
'excludeBundles' => [
\mihaildev\ckeditor\Assets::class,

// \app\helloworld\AssetBundle::class, // exclude this bundle from minification
],
],
?>
`

Ignoring conditional tag for js files

When i am using plugin with this configuration:

'class' => '\rmrevin\yii\minify\View',
            'enableMinify' => true,
            'minifyJs' => true,
            'minifyCss' => false,
            'web_path' => '', // path alias to web base
            'base_path' => '@frontend/web', // path alias to web base
            'minify_path' => '@frontend/web/assets/minify', // path alias to save minify result
            'js_position' => [ \yii\web\View::POS_END ], // positions of js files to be minified
            'force_charset' => 'UTF-8', // charset forcibly assign, otherwise will use all of the files found charset
            //'expand_imports' => true, // whether to change @import on content
            'compress_output' => true, // compress result html page

conditional tag for html5shiv and selectivizr are missing. Assets are added like that:

class ShivAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [];
    public $js = [
        'assets/js/html5shiv.min.js'
    ];
    public $jsOptions = ['condition' => 'lte IE 9', 'position' => \yii\web\View::POS_HEAD];
    public $depends = [
        'yii\web\JqueryAsset',
    ];
}

when i am changing back minifyJs to true - conditions are visible.

Минификатор срабатывает каждый раз при аякс запросе

Минификатор срабатывает каждый раз при аякс запросе. Получается что каждый запрос генерируется js файл в папке minify.

  • в контроллере используется $this->renderPartial
  • бандл подключается только в шапке
  • папка web/assets очищена

upd. если используется POS_HEAD, то проблемы не возникает

Ошибка с расширением imperavi-widget

Добрый день! Проблема с расширением https://github.com/vova07/yii2-imperavi-widget(оно работает нормально)
Проблема в том, что Ваше расширение пытается получить доступ к несуществующему файлу,
и выбрасывает исключение sha1_file(.../46523e8f/lang/en.js): failed to open stream: No such file or directory
в строке 341,
там выполняется код $result .= sha1_file(\Yii::getAlias($this->base_path) . $file);

Проблему решит добавление проверки на существование файла, перед его использованием

Форкнуть и исправить - решение, но неохота дубликаты плодить))

minify html

hi html minify have a problem . when i try it with this html:

use hoomanMirghasemi\jdf\Jdf;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\models\BaseUser;
use common\models\Country;
use common\models\State;
use common\models\CashReport;
use common\models\LoginForm;
use common\models\SearchInfo;
use common\widgets\Alert;
use yii\web\View;
use frontend\assets\AppAsset;
use yii\bootstrap\ActiveForm;

$this->registerJsFile("/js/jquery.autosize.js");
$this->registerJsFile(PROTOCOL.DOMAIN."/bootstrap/js/bootstrap.rtl.js", ['position'=>View::POS_END]);
if (Yii::$app->params['analytics']) {
$this->registerJsFile("/js/google-analytics.js", ['position'=>View::POS_END]);
}

$this->registerJsFile("/js/menu_xs/modernizr.custom.25376.js", ['position'=>View::POS_END]);
$this->registerJsFile("/js/menu_xs/classie.js", ['position'=>View::POS_END]);
$this->registerJsFile("/js/menu_xs/menu.js",['position'=>View::POS_END]);
$this->registerJsFile("/js/main.js",['position'=>View::POS_END]);

$this->registerCssFile(PROTOCOL.DOMAIN."/fonts/fontawesome/font-awesome.css");
$this->registerCssFile("/css/main-ask.css");
$this->registerCssFile("/css/login-page.css");
$this->registerCssFile("/css/other-page-header.css");
$this->registerCssFile("/css/footer.css");
$this->registerCssFile("/bootstrap/css/bootstrap.rtl.min.css");

$this->registerCssFile( "/css/cropiframe.css");
$this->registerCssFile("/css/iframe.css");
$this->registerCssFile("/css/menu_xs/normalize.css");
$this->registerCssFile( "/css/menu_xs/demo.css");
$this->registerCssFile("/css/menu_xs/component.css");
$this->registerCssFile("/css/layouts/body-footer2.css");
$this->registerCssFile("/css/layouts/body-footer1.css");
$this->registerCssFile("/css/layouts/main.css");

AppAsset::register($this);

?>






<title>title) ?></title>





<style>
@font-face {
font-family: 'Btitr';
src: url('/fonts/BTitrBold.eot'); /* IE9 Compatibility Modes /
src: url('/fonts/BTitrBold.eot?') format('eot'), /
IE6-IE8 /
url('/fonts/BTitrBold.woff') format('woff'), /
Modern Browsers /
url('/fonts/BTitrBold.ttf') format('truetype');
}
@font-face {
font-family: 'IRANSans';
src: url('/fonts/IRANSans.eot'); /
IE9 Compatibility Modes /
src: url('/fonts/IRANSans.eot?') format('eot'), /
IE6-IE8 /
url('/fonts/IRANSans.woff') format('woff'), /
Modern Browsers /
url('/fonts/IRANSans.ttf') format('truetype');
}
@font-face {
font-family: 'IRANSansnum';
src: url('/fonts/num/IRANSansWeb(FaNum).eot');
src: url('/fonts/num/IRANSansWeb(FaNum).eot?#iefix') format('eot'), /
IE6–8 /
url('/fonts/num/IRANSansWeb(FaNum).woff2') format('woff2'), /
Chrome36+, Opera24+/
url('/fonts/num/IRANSansWeb(FaNum).woff') format('woff'), /
FF3.6+, IE9, Chrome6+, Saf5.1+/
url('/fonts/num/IRANSansWeb(FaNum).ttf') format('ttf');
font-weight: normal;
}
@font-face {
font-family: 'Bkoodak';
src: url('/fonts/BKoodakBold.eot'); /
IE9 Compatibility Modes /
src: url('/fonts/BKoodakBold.eot?') format('eot'), /
IE6-IE8 /
url('/fonts/BKoodakBold.woff') format('woff'), /
Modern Browsers */
url('/fonts/BKoodakBold.ttf') format('truetype');
}
</style>
params['searchEngineIndex']): ?>




params['alexa']): ?>
<script type="text/javascript">
_atrk_opts = {atrk_acct: "6DHQm1a4KM+25T", domain: "salamatyar.com", dynamic: true};
(function () {
var as = document.createElement('script');
as.type = 'text/javascript';
as.async = true;
as.src = "https://d31qbv1cthcecs.cloudfront.net/atrk.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(as, s);
})();
</script>


head() ?>

<div id="perspective" class="perspective effect-moveleft">

    <nav class="outer-nav right vertical">
        <ul class="nav navbar-nav bg_navbar visible-xs">
            <li class="margin-li-menu media-menu-margin margin_right">
                <a href="<?= PROTOCOL.DOMAIN  ?>" class="third after add" title="سلامتیار">
                    <i class="fa fa-home fa-home_menu_xs"></i><span class="text">خانه</span>
                </a>
            </li>
            

        </ul>
    </nav>
</div><!-- /perspective -->
<?php $this->endBody() ?>
</body>
</html>
endPage() ?>

this work

and with this html:

registerJsFile("/js/jquery.autosize.js"); $this->registerJsFile(PROTOCOL.DOMAIN."/bootstrap/js/bootstrap.rtl.js", ['position'=>View::POS_END]); if (Yii::$app->params['analytics']) { $this->registerJsFile("/js/google-analytics.js", ['position'=>View::POS_END]); } $this->registerJsFile("/js/menu_xs/modernizr.custom.25376.js", ['position'=>View::POS_END]); $this->registerJsFile("/js/menu_xs/classie.js", ['position'=>View::POS_END]); $this->registerJsFile("/js/menu_xs/menu.js",['position'=>View::POS_END]); $this->registerJsFile("/js/main.js",['position'=>View::POS_END]); $this->registerCssFile(PROTOCOL.DOMAIN."/fonts/fontawesome/font-awesome.css"); $this->registerCssFile("/css/main-ask.css"); $this->registerCssFile("/css/login-page.css"); $this->registerCssFile("/css/other-page-header.css"); $this->registerCssFile("/css/footer.css"); $this->registerCssFile("/bootstrap/css/bootstrap.rtl.min.css"); $this->registerCssFile( "/css/cropiframe.css"); $this->registerCssFile("/css/iframe.css"); $this->registerCssFile("/css/menu_xs/normalize.css"); $this->registerCssFile( "/css/menu_xs/demo.css"); $this->registerCssFile("/css/menu_xs/component.css"); $this->registerCssFile("/css/layouts/body-footer2.css"); $this->registerCssFile("/css/layouts/body-footer1.css"); $this->registerCssFile("/css/layouts/main.css"); AppAsset::register($this); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <meta name="language" content="fa" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="HandheldFriendly" content="true"/>
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <meta name="google-site-verification" content="oKj208q33gcuWhG0Oaaf5Ok3_2pNChW9QGwOkkPMSa4" />
    <style>
        @font-face {
            font-family: 'Btitr';
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/BTitrBold.eot'); /* IE9 Compatibility Modes */
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/BTitrBold.eot?') format('eot'), /* IE6-IE8 */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/BTitrBold.woff') format('woff'), /* Modern Browsers */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/BTitrBold.ttf') format('truetype');
        }
        @font-face {
            font-family: 'IRANSans';
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/IRANSans.eot'); /* IE9 Compatibility Modes */
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/IRANSans.eot?') format('eot'), /* IE6-IE8 */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/IRANSans.woff') format('woff'), /* Modern Browsers */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/IRANSans.ttf') format('truetype');
        }
        @font-face {
            font-family: 'IRANSansnum';
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/num/IRANSansWeb(FaNum).eot');
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/num/IRANSansWeb(FaNum).eot?#iefix') format('eot'),  /* IE6–8 */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/num/IRANSansWeb(FaNum).woff2') format('woff2'),  /* Chrome36+, Opera24+*/
            url('<?= PROTOCOL.DOMAIN ?>/fonts/num/IRANSansWeb(FaNum).woff') format('woff'),  /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
            url('<?= PROTOCOL.DOMAIN ?>/fonts/num/IRANSansWeb(FaNum).ttf') format('ttf');
            font-weight: normal;
        }
        @font-face {
            font-family: 'Bkoodak';
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/BKoodakBold.eot'); /* IE9 Compatibility Modes */
            src: url('<?= PROTOCOL.DOMAIN ?>/fonts/BKoodakBold.eot?') format('eot'), /* IE6-IE8 */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/BKoodakBold.woff') format('woff'), /* Modern Browsers */
            url('<?= PROTOCOL.DOMAIN ?>/fonts/BKoodakBold.ttf') format('truetype');
        }
    </style>
    <?php if (Yii::$app->params['searchEngineIndex']): ?>
        <meta content="INDEX,FOLLOW" name="robots">
    <?php else: ?>
        <meta content="NOINDEX, NOFOLLOW" name="robots">
    <?php endif; ?>
    <?php if (Yii::$app->params['alexa']): ?>
        <script type="text/javascript">
            _atrk_opts = {atrk_acct: "6DHQm1a4KM+25T", domain: "salamatyar.com", dynamic: true};
            (function () {
                var as = document.createElement('script');
                as.type = 'text/javascript';
                as.async = true;
                as.src = "https://d31qbv1cthcecs.cloudfront.net/atrk.js";
                var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(as, s);
            })();
        </script>
        <noscript><img src="https://d5nxst8fruw4z.cloudfront.net/atrk.gif?account=6DHQm1a4KM+25T" style="display:none" height="1" width="1" alt="" /></noscript>
    <?php endif; ?>
    <?php $this->head() ?>
</head>
<body>

<div id="perspective" class="perspective effect-moveleft">

    <nav class="outer-nav right vertical">
        <ul class="nav navbar-nav bg_navbar visible-xs">
            <li class="margin-li-menu media-menu-margin margin_right">
                <a href="<?= PROTOCOL.DOMAIN  ?>" class="third after add" title="سلامتیار">
                    <i class="fa fa-home fa-home_menu_xs"></i><span class="text">خانه</span>
                </a>
            </li>
            <li class="margin-li-menu">
                <a href="<?=  PROTOCOL.DOMAIN .'/doctors'  ?>" class="third after add" title="پزشکان سلامتیار">
                    <i class="fa fa-user-md fa-user-md_menu_xs"></i><span class="text">پزشکان سلامتیار</span>
                </a>
            </li>

        </ul>
    </nav>
</div><!-- /perspective -->
<?php $this->endBody() ?>
</body>
</html>
endPage() ?>

it is not working!!

see diffrent of that tow code only addtional li

php 8 problem

you lock mrclay/minify to version 3.0.7
and for it can not use php 8

base64 in css

base64 svg and other images in css, minify non correct. but if move it into pure html img tag it pass correctly.

Minification without joining files together

Hi Roman,
Thank you for your plugin. I’d like to ask you if you’d consider one additional feature – compressing files without joining them together. I actually thing, the concentration is really bad idea here.
Just imagine even simple web. It has 20 pages. On every page there is a different combination of js/css plugins/codes.

If we don’t join them together, every file is only compressed (that’s always a god idea) but separated. It may look like disadvantage, because we created another http requests, but it’s only the first loading and to be honest, it’s usually not such a big deal.
But what will happen, when we loads the second, third and etc page? Every time the page requests any from the previously generated file, It’ll be served from cache. And that’s great. The separation different pieces of code to different files, which can be loaded on different pages, is really good approach here.

But on the other hand, if we join the files together, it means for every different combination of files, there is a different output file. It means that the code is duplicated enormously. More files, more combinations, more different outputs. When we visit the pages, we have to load the new files all the time again, because they are different – made from different parts.

Me for example - I have my main js and css files, which are generated outside of Yii by gulp. They are actually combinations of many parts. So you see that doesn’t mean I’m against the joining technique. It’s great, but it has to be used carefully. My using is helpful, because my finale js and css files are the only one for the whole web. User loads only one file and can avoid loading tons of js and css request.

But in your case, a lot of different files are created. Imagine, my main JS file has 200kB. On one page, Yii adds some little 1k plugin. User has to download new 201kB file. On the other page, there is another small plugin from Yii which has 5k. User have download again 205kB. No matter he has already downloaded it before. This is now part a new combination.

:-/ So that bothers me. I understand the need Yii adds assets dynamically. It’s not possible to use everything, if they don’t know, what we are gonna use. But the joining approach, which is great for situations when you preparing a layout for example, doesn’t suits here.
So what do you think about that? Am I missing something?

Wil be glad for any response.

Update README.md

The line
"rmrevin/yii2-minify-view": "~2.13",

should be
"rmrevin/yii2-minify-view": "~1.13",

otherwise, composer will return error as that version simply doesn't exists.

How to use this in development environment?

First, thank you for this awesome extension.

It works like a charm, but i can't use this in development environment, when I don't want to minify the stylesheets and javascripts.

I can't overwrite the view component's settings in the main-local.php because your View class has extra attributes.

I think it would be great to have an extra attribute like 'disable' => true

Or if you have an existing solution for development environments please share with us! Thank you!

JS is missing on certain page loads

If I load page A on a clean @webroot\minify directory, everything works fine. If I load page B after that it seems to have problems loading some of the JS with parts of it missing, generating JS errors in the console. If I wipe the @webroot\minify directory and then load page B, it works fine, but then when I try load page A, it breaks in the same way.

I will try do some more investigation when I get time and add more details to this issue report.

Скорость....

Все работает отлично, но есть одно "но": слишком много времени уходит на "компиляцию" файлов. Потом все летает, но вот первый заход на страницу длится около 10-15 секунд даже на локальной машине (nginx + php7). А страница с TinyMCE генерировалась 46 секунд. :(

Это слишком медленно.

Я в коде не рылся, но как я понял, скрипт производит полную "компиляцию" при любом, даже малейшем изменении в списке минифицируемых файлов. Т.е. есть страница, которой нужны jQuery и Bootstrap, для нее скрипт уже собрал пакеты и на других страницах с такими же запросами будут отдаваться уже собранные пакеты, но если новая страница хочет те же jQuery и Bootstrap и еще один маленький файл стилей, то весь процесс сборки для нее начинается с начала. :-(

Как Вам такой вариант: при сборке скрипт минифицирует каждый файл (jquery.js, bootstrap.css и т.д.) отдельно и складывает их в специальную папку внутри runtime. А затем просто склеивает их в наборы для конкретных страниц (как и сейчас). Т.е. для описанного выше случая, когда страница хочет jQuery и Bootstrap и еще один маленький файл стилей, скрипту не придется минифицировать все - достаточно прогнать минификацию только для маленького файла стилей, а затем склеить пакеты из уже минифицированных ранее файлов jQuery и Bootstrap.

Это должно дать хороший прирост в скорости. Что думаете?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.