2

I want to load all the css files separately only for IE 9 is there a way to tell Magento to do that? is there a call I can write in the head file to call all the needed css files? to clarify I want to put in a call like that that gets the css unmerged

<!--[if lt IE 10]>
<?php echo $this->getCssJsHtml() ?>
  • that mean you does not want to css merge for IE9 – Amit Bera Oct 7 '15 at 15:19
  • yes exactly what i need – Yehuda Schwartz Oct 7 '15 at 15:24
2

In order to fulfill your requirement you need customization/rewrite at class Mage_Page_Block_Html_Head ,magento did not have any function of which accomplice the requirement

As per as default magento behave js/css files are rendered/merge by getCssJsHtml() on this cass.

On this function basic of configuration value Mage::getStoreConfigFlag('dev/css/merge_css_files') css files are merge.

the value is store in a variable $shouldMergeCss = Mage::getStoreConfigFlag('dev/css/merge_css_files');

So let make $shouldMergeCss value false whenever user agent is IE9

// track Ie9 Browser then make merge css false; 
if(preg_match('/(?i)msie [9-9]/',Mage::helper('core/http')->getHttpUserAgent())):
    $shouldMergeCss =false;
else:
    $shouldMergeCss = Mage::getStoreConfigFlag('dev/css/merge_css_files');
endif;

Code:

config.xml code:

<?xml version="1.0" encoding="utf-8"?>
<config>
....
  <global>
      <blocks>
          <page>
              <rewrite>
                  <html_head>[ModuleNameSpace]_[Modulename]_Block_Page_Html_Head</html_head>
              </rewrite>
          </page>
      </blocks>
  </global>
  .....
</config>

rewrite class

<?php
class [ModuleNameSpace]_[Modulename]_Block_Page_Html_Head extends Mage_Page_Block_Html_Head{
    public function getCssJsHtml()
    {
        // separate items by types
        $lines  = array();
        foreach ($this->_data['items'] as $item) {
            if (!is_null($item['cond']) && !$this->getData($item['cond']) || !isset($item['name'])) {
                continue;
            }
            $if     = !empty($item['if']) ? $item['if'] : '';
            $params = !empty($item['params']) ? $item['params'] : '';
            switch ($item['type']) {
                case 'js':        // js/*.js
                case 'skin_js':   // skin/*/*.js
                case 'js_css':    // js/*.css
                case 'skin_css':  // skin/*/*.css
                    $lines[$if][$item['type']][$params][$item['name']] = $item['name'];
                    break;
                default:
                    $this->_separateOtherHtmlHeadElements($lines, $if, $item['type'], $params, $item['name'], $item);
                    break;
            }
        }

        // prepare HTML


      $shouldMergeJs = Mage::getStoreConfigFlag('dev/js/merge_files');

      // track Ie9 Browser then make merge css false; 
       if(preg_match('/(?i)msie [8-8]/',Mage::helper('core/http')->getHttpUserAgent())):
      $shouldMergeCss =false;
      else:
      $shouldMergeCss = Mage::getStoreConfigFlag('dev/css/merge_css_files');
      endif;

        $html   = '';
        foreach ($lines as $if => $items) {
            if (empty($items)) {
                continue;
            }
            if (!empty($if)) {
                // open !IE conditional using raw value
                if (strpos($if, "><!-->") !== false) {
                    $html .= $if . "\n";
                } else {
                    $html .= '<!--[if '.$if.']>' . "\n";
                }
            }

            // static and skin css
            $html .= $this->_prepareStaticAndSkinElements('<link rel="stylesheet" type="text/css" href="%s"%s />'."\n",
                empty($items['js_css']) ? array() : $items['js_css'],
                empty($items['skin_css']) ? array() : $items['skin_css'],
                $shouldMergeCss ? array(Mage::getDesign(), 'getMergedCssUrl') : null
            );

            // static and skin javascripts
            $html .= $this->_prepareStaticAndSkinElements('<script type="text/javascript" src="%s"%s></script>' . "\n",
                empty($items['js']) ? array() : $items['js'],
                empty($items['skin_js']) ? array() : $items['skin_js'],
                $shouldMergeJs ? array(Mage::getDesign(), 'getMergedJsUrl') : null
            );

            // other stuff
            if (!empty($items['other'])) {
                $html .= $this->_prepareOtherHtmlHeadElements($items['other']) . "\n";
            }

            if (!empty($if)) {
                // close !IE conditional comments correctly
                if (strpos($if, "><!-->") !== false) {
                    $html .= '<!--<![endif]-->' . "\n";
                } else {
                    $html .= '<![endif]-->' . "\n";
                }
            }
        }
        return $html;
    }
}
  • please check update.. – Amit Bera Oct 7 '15 at 17:32
  • You donot use <!--[if lt IE 10]> before4<?php echo $this->getCssJsHtml() ?> – Amit Bera Oct 7 '15 at 17:38
0

Copy the below code and create a file named Head.php and place it under app\code\local\Mage\Page\Block\Html

<?php
    class Mage_Page_Block_Html_Head extends Mage_Core_Block_Template
    {
        /**
         * Initialize template
         *
         */
        protected function _construct()
        {
            $this->setTemplate('page/html/head.phtml');
        }

        /**
         * Add CSS file to HEAD entity
         *
         * @param string $name
         * @param string $params
         * @return Mage_Page_Block_Html_Head
         */
        public function addCss($name, $params = "")
        {
            $this->addItem('skin_css', $name, $params);
            return $this;
        }

        /**
         * Add JavaScript file to HEAD entity
         *
         * @param string $name
         * @param string $params
         * @return Mage_Page_Block_Html_Head
         */
        public function addJs($name, $params = "")
        {
            $this->addItem('js', $name, $params);
            return $this;
        }

        /**
         * Add CSS file for Internet Explorer only to HEAD entity
         *
         * @param string $name
         * @param string $params
         * @return Mage_Page_Block_Html_Head
         */
        public function addCssIe($name, $params = "")
        {
            $this->addItem('skin_css', $name, $params, 'IE');
            return $this;
        }

        /**
         * Add JavaScript file for Internet Explorer only to HEAD entity
         *
         * @param string $name
         * @param string $params
         * @return Mage_Page_Block_Html_Head
         */
        public function addJsIe($name, $params = "")
        {
            $this->addItem('js', $name, $params, 'IE');
            return $this;
        }

        /**
         * Add Link element to HEAD entity
         *
         * @param string $rel forward link types
         * @param string $href URI for linked resource
         * @return Mage_Page_Block_Html_Head
         */
        public function addLinkRel($rel, $href)
        {
            $this->addItem('link_rel', $href, 'rel="' . $rel . '"');
            return $this;
        }

        /**
         * Add HEAD Item
         *
         * Allowed types:
         *  - js
         *  - js_css
         *  - skin_js
         *  - skin_css
         *  - rss
         *
         * @param string $type
         * @param string $name
         * @param string $params
         * @param string $if
         * @param string $cond
         * @return Mage_Page_Block_Html_Head
         */
        public function addItem($type, $name, $params=null, $if=null, $cond=null)
        {
            if ($type==='skin_css' && empty($params)) {
                $params = 'media="all"';
            }
            $this->_data['items'][$type.'/'.$name] = array(
                'type'   => $type,
                'name'   => $name,
                'params' => $params,
                'if'     => $if,
                'cond'   => $cond,
           );
            return $this;
        }

        /**
         * Remove Item from HEAD entity
         *
         * @param string $type
         * @param string $name
         * @return Mage_Page_Block_Html_Head
         */
        public function removeItem($type, $name)
        {
            unset($this->_data['items'][$type.'/'.$name]);
            return $this;
        }

        /**
         * Get HEAD HTML with CSS/JS/RSS definitions
         * (actually it also renders other elements, TODO: fix it up or rename this method)
         *
         * @return string
         */
        public function getCssJsHtml()
        {
            // separate items by types
            $lines  = array();
            foreach ($this->_data['items'] as $item) {
                if (!is_null($item['cond']) && !$this->getData($item['cond']) || !isset($item['name'])) {
                    continue;
                }
                $if     = !empty($item['if']) ? $item['if'] : '';
                $params = !empty($item['params']) ? $item['params'] : '';
                switch ($item['type']) {
                    case 'js':        // js/*.js
                    case 'skin_js':   // skin/*/*.js
                    case 'js_css':    // js/*.css
                    case 'skin_css':  // skin/*/*.css
                        $lines[$if][$item['type']][$params][$item['name']] = $item['name'];
                        break;
                    default:
                        $this->_separateOtherHtmlHeadElements($lines, $if, $item['type'], $params, $item['name'], $item);
                        break;
                }
            }

            // prepare HTML
            $shouldMergeJs = Mage::getStoreConfigFlag('dev/js/merge_files');
            $shouldMergeCss = Mage::getStoreConfigFlag('dev/css/merge_css_files');
            $html   = '';
            foreach ($lines as $if => $items) {
                if (empty($items)) {
                    continue;
                }
                if (!empty($if)) {
                    // open !IE conditional using raw value
                    if (strpos($if, "><!-->") !== false) {
                        $html .= $if . "\n";
                    } else {
                        $html .= '<!--[if '.$if.']>' . "\n";
                    }
                }

                // static and skin css
                if($this->browser() !="IE9.0"):
                    $html .= $this->_prepareStaticAndSkinElements('<link rel="stylesheet" type="text/css" href="%s"%s />'."\n",
                        empty($items['js_css']) ? array() : $items['js_css'],
                        empty($items['skin_css']) ? array() : $items['skin_css'],
                        $shouldMergeCss ? array(Mage::getDesign(), 'getMergedCssUrl') : null
                    );
                else:
                    $html .= $this->_prepareStaticAndSkinElements('<link rel="stylesheet" type="text/css" href="%s"%s />'."\n",
                        empty($items['js_css']) ? array() : $items['js_css'],
                        empty($items['skin_css']) ? array() : $items['skin_css']
                    );
                endif;

                // static and skin javascripts
                $html .= $this->_prepareStaticAndSkinElements('<script type="text/javascript" src="%s"%s></script>' . "\n",
                    empty($items['js']) ? array() : $items['js'],
                    empty($items['skin_js']) ? array() : $items['skin_js'],
                    $shouldMergeJs ? array(Mage::getDesign(), 'getMergedJsUrl') : null
                );

                // other stuff
                if (!empty($items['other'])) {
                    $html .= $this->_prepareOtherHtmlHeadElements($items['other']) . "\n";
                }

                if (!empty($if)) {
                    // close !IE conditional comments correctly
                    if (strpos($if, "><!-->") !== false) {
                        $html .= '<!--<![endif]-->' . "\n";
                    } else {
                        $html .= '<![endif]-->' . "\n";
                    }
                }
            }
            return $html;
        }

        /**
         * Merge static and skin files of the same format into 1 set of HEAD directives or even into 1 directive
         *
         * Will attempt to merge into 1 directive, if merging callback is provided. In this case it will generate
         * filenames, rather than render urls.
         * The merger callback is responsible for checking whether files exist, merging them and giving result URL
         *
         * @param string $format - HTML element format for sprintf('<element src="%s"%s />', $src, $params)
         * @param array $staticItems - array of relative names of static items to be grabbed from js/ folder
         * @param array $skinItems - array of relative names of skin items to be found in skins according to design config
         * @param callback $mergeCallback
         * @return string
         */
        protected function &_prepareStaticAndSkinElements($format, array $staticItems, array $skinItems,
                                                          $mergeCallback = null)
        {
            $designPackage = Mage::getDesign();
            $baseJsUrl = Mage::getBaseUrl('js');
            $items = array();
            if ($mergeCallback && !is_callable($mergeCallback)) {
                $mergeCallback = null;
            }

            // get static files from the js folder, no need in lookups
            foreach ($staticItems as $params => $rows) {
                foreach ($rows as $name) {
                    $items[$params][] = $mergeCallback ? Mage::getBaseDir() . DS . 'js' . DS . $name : $baseJsUrl . $name;
                }
            }

            // lookup each file basing on current theme configuration
            foreach ($skinItems as $params => $rows) {
                foreach ($rows as $name) {
                    $items[$params][] = $mergeCallback ? $designPackage->getFilename($name, array('_type' => 'skin'))
                        : $designPackage->getSkinUrl($name, array());
                }
            }

            $html = '';
            foreach ($items as $params => $rows) {
                // attempt to merge
                $mergedUrl = false;
                if ($mergeCallback) {
                    $mergedUrl = call_user_func($mergeCallback, $rows);
                }
                // render elements
                $params = trim($params);
                $params = $params ? ' ' . $params : '';
                if ($mergedUrl) {
                    $html .= sprintf($format, $mergedUrl, $params);
                } else {
                    foreach ($rows as $src) {
                        $html .= sprintf($format, $src, $params);
                    }
                }
            }
            return $html;
        }

        /**
         * Classify HTML head item and queue it into "lines" array
         *
         * @see self::getCssJsHtml()
         * @param array &$lines
         * @param string $itemIf
         * @param string $itemType
         * @param string $itemParams
         * @param string $itemName
         * @param array $itemThe
         */
        protected function _separateOtherHtmlHeadElements(&$lines, $itemIf, $itemType, $itemParams, $itemName, $itemThe)
        {
            $params = $itemParams ? ' ' . $itemParams : '';
            $href   = $itemName;
            switch ($itemType) {
                case 'rss':
                    $lines[$itemIf]['other'][] = sprintf('<link href="%s"%s rel="alternate" type="application/rss+xml" />',
                        $href, $params
                    );
                    break;
                case 'link_rel':
                    $lines[$itemIf]['other'][] = sprintf('<link%s href="%s" />', $params, $href);
                    break;
            }
        }

        /**
         * Render arbitrary HTML head items
         *
         * @see self::getCssJsHtml()
         * @param array $items
         * @return string
         */
        protected function _prepareOtherHtmlHeadElements($items)
        {
            return implode("\n", $items);
        }

        /**
         * Retrieve Chunked Items
         *
         * @param array $items
         * @param string $prefix
         * @param int $maxLen
         * @return array
         */
        public function getChunkedItems($items, $prefix = '', $maxLen = 450)
        {
            $chunks = array();
            $chunk  = $prefix;
            foreach ($items as $item) {
                if (strlen($chunk.','.$item)>$maxLen) {
                    $chunks[] = $chunk;
                    $chunk = $prefix;
                }
                $chunk .= ','.$item;
            }
            $chunks[] = $chunk;
            return $chunks;
        }

        /**
         * Retrieve Content Type
         *
         * @return string
         */
        public function getContentType()
        {
            if (empty($this->_data['content_type'])) {
                $this->_data['content_type'] = $this->getMediaType().'; charset='.$this->getCharset();
            }
            return $this->_data['content_type'];
        }

        /**
         * Retrieve Media Type
         *
         * @return string
         */
        public function getMediaType()
        {
            if (empty($this->_data['media_type'])) {
                $this->_data['media_type'] = Mage::getStoreConfig('design/head/default_media_type');
            }
            return $this->_data['media_type'];
        }

        /**
         * Retrieve Charset
         *
         * @return string
         */
        public function getCharset()
        {
            if (empty($this->_data['charset'])) {
                $this->_data['charset'] = Mage::getStoreConfig('design/head/default_charset');
            }
            return $this->_data['charset'];
        }

        /**
         * Set title element text
         *
         * @param string $title
         * @return Mage_Page_Block_Html_Head
         */
        public function setTitle($title)
        {
            $this->_data['title'] = Mage::getStoreConfig('design/head/title_prefix') . ' ' . $title
                . ' ' . Mage::getStoreConfig('design/head/title_suffix');
            return $this;
        }

        /**
         * Retrieve title element text (encoded)
         *
         * @return string
         */
        public function getTitle()
        {
            if (empty($this->_data['title'])) {
                $this->_data['title'] = $this->getDefaultTitle();
            }
            return htmlspecialchars(html_entity_decode(trim($this->_data['title']), ENT_QUOTES, 'UTF-8'));
        }

        /**
         * Retrieve default title text
         *
         * @return string
         */
        public function getDefaultTitle()
        {
            return Mage::getStoreConfig('design/head/default_title');
        }

        /**
         * Retrieve content for description tag
         *
         * @return string
         */
        public function getDescription()
        {
            if (empty($this->_data['description'])) {
                $this->_data['description'] = Mage::getStoreConfig('design/head/default_description');
            }
            return $this->_data['description'];
        }

        /**
         * Retrieve content for keyvords tag
         *
         * @return string
         */
        public function getKeywords()
        {
            if (empty($this->_data['keywords'])) {
                $this->_data['keywords'] = Mage::getStoreConfig('design/head/default_keywords');
            }
            return $this->_data['keywords'];
        }

        /**
         * Retrieve URL to robots file
         *
         * @return string
         */
        public function getRobots()
        {
            if (empty($this->_data['robots'])) {
                $this->_data['robots'] = Mage::getStoreConfig('design/head/default_robots');
            }
            return $this->_data['robots'];
        }

        /**
         * Get miscellanious scripts/styles to be included in head before head closing tag
         *
         * @return string
         */
        public function getIncludes()
        {
            if (empty($this->_data['includes'])) {
                $this->_data['includes'] = Mage::getStoreConfig('design/head/includes');
            }
            return $this->_data['includes'];
        }

        /**
         * Getter for path to Favicon
         *
         * @return string
         */
        public function getFaviconFile()
        {
            if (empty($this->_data['favicon_file'])) {
                $this->_data['favicon_file'] = $this->_getFaviconFile();
            }
            return $this->_data['favicon_file'];
        }

        /**
         * Retrieve path to Favicon
         *
         * @return string
         */
        protected function _getFaviconFile()
        {
            $folderName = Mage_Adminhtml_Model_System_Config_Backend_Image_Favicon::UPLOAD_DIR;
            $storeConfig = Mage::getStoreConfig('design/head/shortcut_icon');
            $faviconFile = Mage::getBaseUrl('media') . $folderName . '/' . $storeConfig;
            $absolutePath = Mage::getBaseDir('media') . '/' . $folderName . '/' . $storeConfig;

            if(!is_null($storeConfig) && $this->_isFile($absolutePath)) {
                $url = $faviconFile;
            } else {
                $url = $this->getSkinUrl('favicon.ico');
            }
            return $url;
        }

        /**
         * If DB file storage is on - find there, otherwise - just file_exists
         *
         * @param string $filename
         * @return bool
         */
        protected function _isFile($filename) {
            if (Mage::helper('core/file_storage_database')->checkDbUsage() && !is_file($filename)) {
                Mage::helper('core/file_storage_database')->saveFileToFilesystem($filename);
            }
            return is_file($filename);
        }

        public function browser() {
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $browsers = array(
                                'Chrome' => array('Google Chrome','Chrome/(.*)\s'),
                                'MSIE' => array('IE','MSIE\s([0-9\.]*)'),
                                'Firefox' => array('Firefox', 'Firefox/([0-9\.]*)'),
                                'Safari' => array('Safari', 'Version/([0-9\.]*)'),
                                'Opera' => array('Opera', 'Version/([0-9\.]*)')
                                ); 

            $browser_details = array();

                foreach ($browsers as $browser => $browser_info){
                    if (preg_match('@'.$browser.'@i', $user_agent)){
                        $browser_details['name'] = $browser_info[0];
                            preg_match('@'.$browser_info[1].'@i', $user_agent, $version);
                        $browser_details['version'] = $version[1];
                            break;
                    } else {
                        $browser_details['name'] = 'Unknown';
                        $browser_details['version'] = 'Unknown';
                    }
                }

            return $browser_details['name'].$browser_details['version'];
        }
    }

CSS files will not merge for IE9 browser. Working for me. Try it at your end.

  • 1
    Please explain in detail what you did and where instead of posting the whole class. I would advice people not to just copy paste the code since you don't know what might be in there – Sander Mangel Oct 7 '15 at 17:52
0

ok i added

<!--[if lt IE 10]>
<?php echo $this->getIeCssJsHtml() ?>
<![endif]-->

to head.phtml

and made a module with block/Head.php:

class Company_IeFix_Block_Head extends Mage_Page_Block_Html_Head
{
        public function getIeCssJsHtml()
    {
        // separate items by types
        $lines  = array();
        foreach ($this->_data['items'] as $item) {
            if (!is_null($item['cond']) && !$this->getData($item['cond']) || !isset($item['name'])) {
                continue;
            }
            $if     = !empty($item['if']) ? $item['if'] : '';
            $params = !empty($item['params']) ? $item['params'] : '';
            switch ($item['type']) {
                case 'js':        // js/*.js
                case 'skin_js':   // skin/*/*.js
                case 'js_css':    // js/*.css
                case 'skin_css':  // skin/*/*.css
                    $lines[$if][$item['type']][$params][$item['name']] = $item['name'];
                    break;
                default:
                    $this->_separateOtherHtmlHeadElements($lines, $if, $item['type'], $params, $item['name'], $item);
                    break;
            }
        }

        // prepare HTML
        $shouldMergeCss = false;
        $html   = '';
        foreach ($lines as $if => $items) {
            if (empty($items)) {
                continue;
            }
            if (!empty($if)) {
                $html .= '<!--[if '.$if.']>'."\n";
            }

            // static and skin css
            $html .= $this->_prepareStaticAndSkinElements('<link rel="stylesheet" type="text/css" href="%s"%s />' . "\n",
                empty($items['js_css']) ? array() : $items['js_css'],
                empty($items['skin_css']) ? array() : $items['skin_css'],
                $shouldMergeCss ? array(Mage::getDesign(), 'getMergedCssUrl') : null
            );

            // static and skin javascripts


            // other stuff
            if (!empty($items['other'])) {
                $html .= $this->_prepareOtherHtmlHeadElements($items['other']) . "\n";
            }

            if (!empty($if)) {
                $html .= '<![endif]-->'."\n";
            }
        }
        return $html;
    }
}
and config
<?xml version="1.0"?>
<config>
    <modules>
        <Company_IeFix>
            <version>0.9</version>
        </Company_IeFix>
    </modules>
    <global>
        <blocks>
            <iefix>
                <class>Company_IeFix_Block</class>
            </iefix>
            <page>
                <rewrite>
                    <html_head>Company_IeFix_Block_Head</html_head>
                </rewrite>
            </page>
        </blocks>
    </global>
</config>
  • 1
    This is basically what other users suggested you to do. Please accept one of their answers since they put a lot of effort into taking time to answer questions – Sander Mangel Oct 7 '15 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.