Those days with IE

Time:2021-5-7

Those days with IE

This is the ninety-first original without water. If you want to get more original and good articles, please search the official account to pay attention to us.Those days with IE

preface

Internet Explorer (ie) isMicrosoft CorporationFor the sake of confrontationNetscape browserNetscape Navigator, which was put into development and launched in 1995, once became a rogue software bundled with Windows system, and also occupied a very high market share. However, in recent years, it has been criticized by many users and developers for its backwardness.

Nowadays, even Microsoft has given up updating ie, but many web developers still have to be downward compatible for some users who still insist on using IE browser. The author is also one of them. This article records some adjustments I made to be compatible with IE (IE9 and above) during my work.

Simulate ie version environment

Many developers’ computers are MAC systems, so they can’t install IE browser. At this time, they need to install virtual machine to provide windows environment to test the effect of IE browser. However, the installed virtual machine takes up a lot of space. At this time, you can borrow another windows computer to access itWebpack(or other compiler packer) configuration of the LAN page address, in order to debug, it is also a good choice.

Many domestic browsers also provide fast and compatible dual kernel mode. In fast mode, chrome and other non ie kernels are used, while in compatible mode, ie kernels are used to cope with the use of different pages. When you open the console, you can switch to simulate different ie versions (although it is only simulation, sometimes it is not accurate).

Those days with IE

Style compatible with IE

In fact, many browser incompatibility problems can be solved from this websitecaniuseIt is found that not only ie, but also Safari, Firefox and their browser compatibility in Android system are well summarized here. However, it is very difficult for us to check all the differences at one time and then put into development. Here are some problems I encountered in the development and the corresponding solutions.

1) The picture will deform when the width is fixed and the height is not fixed

When I usually make the first big picture of banner, sometimes for the sake of speed, I write a width directlywidth: 1200pxI think everything is all right. I did well on chorme, and I didn’t live up to my expectations. However, when I tested IE9 and ie10, there was a problem that the image was distorted, as shown in the figure below.

Those days with IE

Those days with IE

When I open the DOM explorer of IE browser, I find that IE browser is very important to me<img />The tag adds an additional attribute like this:width="824" height="300"Where does the width and height come from? I select the downloaded image, right-click to see the details, and find that the width and height of the image file itself are 824px and 300px, so the answer can be known.

When I set the picture labelsrcInternet Explorer automatically sets the width and height of the original image to<img />This causes me to use CSS only to set the width to1200pxWhen it’s not set high,<img />The effective height is the height of the original image300px. And chrome is right<img />Nothing has been added to the label, so the height of the label is the height after scaling according to the image, which will not deform.

  • Performance in Chrome

    Those days with IE

  • Performance under IE

    Those days with IE

The solution is also very simple, that is, in the<img />In the class style of the tag, add a simpleheight: auto;At the same time, set the width and height to cover the width and height automatically added by the original label, which can solve the problem of deformation.

2) 8-bit color value does not work in IE

In the previous development, I was used to using 6-bit color value, and there was no problem. Until one time, the operator feedback that a certain color was selected under the component configuration platform, but it didn’t take effect. Through troubleshooting, I found that the original output color value was 8-bit, and it was the extra two that were not common in IE browser.

Those days with IE

As we know, CSS color is defined by hex notation which combines red, green and blue color values (RGB). The hex value is written with three double digits and starts with # symbol (such as # ff0000). Meanwhile, Chrome browser supports 8-bit color value (such as # ff0000ee) and the last two digitsOpacityAlpha value, where 00 means that the opacity is 0, that is, all transparent state, FF means that the opacity is 100%, that is, all opaque state, but it is not supported in IE browser.

In the case of IE, if you use 8-bit color value, not only the opacity of the last two bits will not take effect, but the entire color setting will not take effect. Here is a simple demo to simulate this situation. The color setting of the title will not take effect, so the default black state will appear.

Those days with IE

Those days with IE

Those days with IE

The solution is also relatively simple. In this scenario, opacity is not necessary. You can delete the last two bits and only use 6-bit color value. If we really need opacity, we can use the RGBA format and use the last bit value to achieve transparency, such asbackground-color: rgba(255,0,0,0.3), even on IE9.

Those days with IE

3) Processing left and right mirror images

IE9 supports many properties of CSS3, but there are still many things that can’t be reached. For example, in one development scenario, I wanted to make two symmetrical patterns on both sides of the title, so I set up the second copy of this picturetransform:rotateY(180deg);Let the image rotate around the Y axis. Although IE9 supports trasform 2D rotation, it does not support trasform 3D rotation, so the following problems will appear.

Those days with IE

Here we can use IE9 supportcanvasThe canvas will flip the axis, draw the image, you can get a symmetrical picture. In HTML, the original<img />The width and height of the label can be set explicitly to ensure the quality of the label<canvas>There is an accurate width and height in the model. The code is as follows.

getRotateImg = (imgSourceId = '') => {
    const imgNode = document.getElementById(imgSourceId);
    const canvas = document.createElement('canvas'); 
    canvas.setAttribute('id', 'canvas');
    //Set the width and height of canvas to prevent deformation 
    canvas.setAttribute('width', imgNode.style.width); 
    canvas.setAttribute('height', imgNode.style.height); 

    const width = parseInt(imgNode.style.width);
    const height = parseInt(imgNode.style.height);
    
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.src = imgNode.src;
    
    imgNode.parentNode.appendChild(canvas); 
    img.onload = function() {
      console.log(imgNode.style.width);
      //Move the coordinate origin to the rightmost end of the canvas to make the reverse image draw to the left and present in the canvas
      ctx.translate(width, 0);
      //Left and right mirror flipped coordinate system
      ctx.scale(-1, 1); 
      ctx.drawImage(img, 0, 0, width, height);
    }
 }

The actual effect is shown in the figure.

Those days with IE

4) Discard flex layout

When you first know flex layout (flexible layout), you will like its flexibility and simplicity, but IE9 does not support flex layout, we can use other ways to replace it.

For example, we can go through this waydisplay: tabledisplay: table-cellTo achieve a simple bisection effect, in this case, the traditional margin can not provide the outer margin, we can useborder-spaceInstead.

Those days with IE

<div class="wrapper-2">
  < div class = "flex-2" > 4 equal parts < / div >
  < div class = "flex-2" > 4 equal parts < / div >
  < div class = "flex-2" > 4 equal parts < / div >
  < div class = "flex-2" > 4 equal parts < / div >
</div>

CSS code

.wrapper-2 {
  height: 100px;
  width: 80%;
  margin: 20px auto;
  background-color: wheat;

  display: table;  /*  Main code*/
  border-spacing: 30px;  /*  Main code*/
}
.flex-2 {
  background-color: pink;
  padding: 10px;
  text-align: center;
  border: solid 2px purple;
  
  display: table-cell; /*  Main code*/
}

Or usetext-align: center,vertical-align: middlecoordinationdisplay: inline-blockThe results are as follows

Those days with IE

.wrapper-3 {
    height: 200px;
    width: 80%;
    margin: 20px auto;
    background-color: wheat;
    line-height: 200px;

    text-align: center; /*  Main code*/
  }
  .flex-3 {
    width: 80px;
    line-height: 100px;
    background-color: pink;
    margin: auto 20px;
    height: 100px;
    border: solid 2px purple;
    text-align: center;

    display: inline-block;   /*  Main code*/
    vertical-align: middle;  /*  Main code*/
    
  }

About CSS hack

The principle of CSS hack is to write different codes according to different browsers and different versions of browsers. There are three common writing methods: conditional annotation method, CSS attribute prefix method and selector prefix method. Generally, the order of writing hack is: from the latest version to the lower version, such as the new version, ie (10 / 9 / 8) and IE (7 / 6). Please refer to this article for specific writing methodsCSS hack collection

But too much dependence on CSS hack will lead to very untidy code, and may leave hidden trouble for subsequent compatibility, so it is rarely used in practice.

For example:

Only in IE
<!--[if IE]>
This text is only displayed in IE browser
<![endif]-->

Only in IE6
<!--[if IE 6]>
This text is only displayed in IE6 browser
<![endif]-->

IE9 does not support history routing

In single page applications, there is the concept of front-end routing. Hash routing has good compatibility, but URL always exists/# It makes people feel a little bit ugly, so we think of a fresh and concise history route.

However, in IE 9, due to the lack of window. History object, it can not be calledhistory.pushStatehistory.replaceStateMethod, so the history routing mode that can be used normally in chrome cannot take effect. At this time, we have several solutions, one is to choose hash routing, the other is to directly make a multi page application, refresh the whole page when jumping, or you can choose to use ithistory.js, which has implemented the common history routing API.

Those days with IE

Using ES6 on IE

@babel/polyfill

Ie does not support many ES6 syntax, such as array. From (), object. Assign (), and other common functions, so we can use toolchainBabelIn@babel/polyfillConvert the code to a syntax that is backward compatible and can be used in lower versions, such as this:

//The original code we wrote
[1, 2, 3].map((n) => n + 1);

//Converted code
[1, 2, 3].map(function(n) {
  return n + 1;
});
npm install --save-dev @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill
  • Use in node environment

    require("babel-polyfill");

  • Use in ES6

    import "babel-polyfill";

  • Using in webpack

    module.exports = {
     entry: ["babel-polyfill", "./app/js"] 
    };

Taking configuration in webpack as an example, the code of webpack.config.js is as follows:

var path = require("path");

module.exports = {
  entry: {
    Entry: ["@ Babel / Polyfill", ". / index. JS"], // add the configuration "@ Babel / Polyfill" before the entry file index. JS
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          Loader: "Babel loader", // Babel loader needs to be installed. This configuration can convert all JS, JSX suffix files
          options: {
            babelrc: false,
            presets: [
              [require. Resolve ("@ Babel / preset env"), {modules: false}], // webpack has done modular packaging, so in modules
            ],
            cacheDirectory: true,
          },
        },
      },
    ],
  },
  plugins: [],
};

summary

The above is the pit I stepped on and the adjustment I made in the process of compatibility with IE (IE9 and above). Technology is dead, but application is alive. We should master the common compatibility ability, but sometimes it’s better to use a more flexible and lower cost way to express downward compatibility. We look forward to many years later, users can give up IE, embrace more agile and easy-to-use browser, and welcome a new era.

Reference documents

JS to achieve compatible IE picture left or right flip

CSS hack collection

invite to one ‘s side men of wisdom and valor

Zooteam, a young, passionate and creative front-end team, belongs to the product R & D Department of Zhengcai cloud. It is located in the picturesque Hangzhou. The team now has more than 40 front-end partners, with an average age of 27 years old. Nearly 30% of them are full stack engineers and young storm group. The members are not only the “old” soldiers from Alibaba and Netease, but also the new recruits from Zhejiang University, China University of science and technology, Hangzhou power and other universities. In addition to the daily business docking, the team also carried out technical exploration and actual combat in the direction of material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.

If you want to change what you have been tossed about, you want to start tossing about; If you want to change, you have been told that you need more ideas, but you can’t break the situation; If you want to change, you have the ability to achieve that result, but do not need you; If you want to change what you want to do, you need a team to support you, but you don’t have the position to lead others; If you want to change the established rhythm, it will be “5 years working time, 3 years working experience”; If you want to change the original understanding is good, but there is always a layer of window paper fuzzy… If you believe in the power of belief, believe that ordinary people can achieve extraordinary things, believe that you can meet a better self. If you want to participate in the process of business take-off and personally promote the growth of a front-end team with in-depth business understanding, perfect technology system, technology creating value and spillover influence, I think we should have a chat. Any time, waiting for you to write something, send it[email protected]

Those days with IE