Sad Puppy 3 브라우저 호환성 문제 해결을 위한 크로스 브라우징 :: 개발자 아지트

1. CSS 크로스 브라우징 해보기

 

CSS 크로스 브라우징 툴인 autoprefixer(https://autoprefixer.github.io)을 사용해서 CSS가 어떻게 바뀌는지 확인해 본다. 

 

git에 따르면, 이걸 npm으로 설치할 수 있어서 brew, npm, nvm으로 설치하고 cli명령어 쳐서 해봤는데 아무일도 일어나지 않았다. 찾아보니까 html파일안에 css코드가 있는 경우 적용이 안된다. 그래서 html코드랑 css코드를 분리했다. 

 

autoprefixer을 실행해봤다. build라는 폴더가 생기고 그 안에 style.css가 생겼다. 



바로 기존 코드와 새로 생긴 코드를 비교해보겠다. 

적용전



적용후

 

 

 음 일단 내 코드에서는 너무 평이한 기능들만 사용해서인지 22번째줄에 주석 말곤 달라진점이 없다.

다음에 기회가 된다면 다음에 한번 더 써봐야겠다. 

 

 

2. 자바스크립트 크로스 브라우징 해보기 

 

Transpiler를 사용해 보고, 자바스크립트 코드가 어떻게 바뀌는지 확인해보기 

Transpiler는 호환성에 맞게해주는 변환기를 말한다. (compiler 같은 기계임)

 

주로 쓰는 Transpiler는 babel과 TypeScript가 있다. 

 

이번에 나는 Babel을 사용해보겠다. 

 

이것도 html안에 script코드가 있으니 적용이 안돼서 app.js파일로 따로 script코드를 분리해줬다. 

 

babel 명령어를 실행하니 dist라는 폴더가 생기고 안에 app.js가 생겼다. 

 

 

 

바로 코드를 비교해보겠다. 

 

변경전 후 코드 확인해보기 

 

확실히 제대로 바뀌는것 같다. ES6이하로 바뀐것을 확인할 수 있다.

 

 

근데 var 위험하다고 선생님이 쓰지말라고 하셨는데,,

 

 

얘가 템플릿 리터럴도 해제시켜버렸다.

 

 

 

전체 코드 비교해보기 

더보기

 

[기존코드]

// window.onload = function(){ ES6 적용전 코드 
window.onload = () =>{ // ES6 적용 코드 
    // 페이지 로드시 localStorage에서 값을 가져와서 출력 
    // 동일한 기능을 하는 걸 함수로 묶어서 개발하는게 좋다. 
    // 나중에 개발하고나서 코드 리뷰를 하면면서 함수 묶으면 좋음
    try {
        // Array.isArray
        let todo = JSON.parse(localStorage.getItem('todo')) || [];
        let check = 0
        // todo값이 배열인지 아닌지만 확인하는 코드도 추가돼야 할거같음 
        if (Array.isArray(todo) == true){
            // 아래는 배열 순회 코드 
            for(let key in todo){
                // key 의 타입은 String 임 
                if ((typeof todo[key] != "undefined") && (todo[key].length > 0)){
                    if ((typeof todo[key] != "undefined") && (todo[key].length > 0)){
                        check = 0;
                    }else{
                        check = 1;
                    }
                }
            }
            if (check == 0){
                displayArray(todo);
            }else{
                console.error('정상적인 접근이 아닙니다.');
            }
        }else{
            console.error('정상적인 접근이 아닙니다.');
        }
        
    } catch (error) {
        console.error('Error parsing JSON from localStorage:', error.message);
        // 이 경우에는 새로운 배열로 초기화할 수 있음
        let todo = [];
        displayArray(todo);
    }
}

function showValue() {
    let inputValue = document.getElementById('inputData').value;
    console.log('inputValue:', inputValue);
    
    let inputLength = inputValue.length;
    
    // 로컬스토리지에서 'todo' 키로 저장된 배열 가져오기 
    let storedArray = JSON.parse(window.localStorage.getItem('todo')) || [];

    let maxLength = 0;

    storedArray.forEach((item, index, storedArray) => {
        if (maxLength < item.length){
            maxLength = item.length;
            console.log('maxLength: ', maxLength);
        }
    });

    let container = document.querySelector('.container');

    if (inputLength >= maxLength){
        container.style.width = `${80 + (inputLength * 10)}px`;
    }else{
        container.style.width = `${80 + (maxLength * 10)}px`;
    }

    container.style.height = `80 + ${(storedArray.length+1) * 20}px`;
    console.log('storedArray:', storedArray);
    
    // 입력값을 배열에 추가함
    storedArray.push(inputValue)

    // localStorage에 값을 저장 
    window.localStorage.setItem('todo', JSON.stringify(storedArray));

    // 입력 필드 초기화 
    document.getElementById('inputData').value = '';

    // 배열 화면에 출력
    displayArray(storedArray);
}

function displayArray(array){
    console.log('displayArray');
    let list = document.getElementById('todoList');
    list.innerHTML = ''; // 기존 리스트 초기화 

    let maxLength = 0;
    
    for(let i = 0; i < array.length; i++){
        if (maxLength < array[i].length){
            maxLength=array[i].length;
            console.log('maxLength: ', maxLength);
        }
    }
    // css에서 클래스 지정하는 함수 
    let container = document.querySelector('.container');
    
    // 삭제하는 기능

    // 템플릿 리터럴 적용
    container.style.width = `${450 + (maxLength * 10)}px`;
    container.style.height = `${80 + ((array.length+1) * 20)}px`;
    
    console.log('array:', array);

    array.forEach(function(item, index){
        // 새로운 리스트 아이템 생성  
        let listItem = document.createElement('li'); 
        // li를 만들고 이를 참조하는 리스트 생성
        let checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        

        let label = document.createElement('label');
        label.textContent = item;

        let deleteButton = document.createElement('button');
        deleteButton.type = "button";
        deleteButton.classList.add('deleteButton');
        deleteButton.textContent = 'x';
        deleteButton.addEventListener('click', function(){
            deleteValue(index);

        });

        listItem.appendChild(label)
        listItem.appendChild(checkbox)
        listItem.appendChild(deleteButton)
        // 리스트에 추가 
        list.appendChild(listItem);
    });
}

function deleteValue(index){

    console.log('hi', index);
    let storedArray = JSON.parse(window.localStorage.getItem('todo')) || [];
    storedArray.splice(index, 1);
    window.localStorage.setItem('todo', JSON.stringify(storedArray));
    displayArray(storedArray);

}

 

 

[babel을 통해 변경된 코드]

"use strict";

// window.onload = function(){ ES6 적용전 코드 
window.onload = function () {
  // ES6 적용 코드 
  // 페이지 로드시 localStorage에서 값을 가져와서 출력 
  // 동일한 기능을 하는 걸 함수로 묶어서 개발하는게 좋다. 
  // 나중에 개발하고나서 코드 리뷰를 하면면서 함수 묶으면 좋음
  try {
    // Array.isArray
    var todo = JSON.parse(localStorage.getItem('todo')) || [];
    var check = 0;
    // todo값이 배열인지 아닌지만 확인하는 코드도 추가돼야 할거같음 
    if (Array.isArray(todo) == true) {
      // 아래는 배열 순회 코드 
      for (var key in todo) {
        // key 의 타입은 String 임 
        if (typeof todo[key] != "undefined" && todo[key].length > 0) {
          if (typeof todo[key] != "undefined" && todo[key].length > 0) {
            check = 0;
          } else {
            check = 1;
          }
        }
      }
      if (check == 0) {
        displayArray(todo);
      } else {
        console.error('정상적인 접근이 아닙니다.');
      }
    } else {
      console.error('정상적인 접근이 아닙니다.');
    }
  } catch (error) {
    console.error('Error parsing JSON from localStorage:', error.message);
    // 이 경우에는 새로운 배열로 초기화할 수 있음
    var _todo = [];
    displayArray(_todo);
  }
};
function showValue() {
  var inputValue = document.getElementById('inputData').value;
  console.log('inputValue:', inputValue);
  var inputLength = inputValue.length;

  // 로컬스토리지에서 'todo' 키로 저장된 배열 가져오기 
  var storedArray = JSON.parse(window.localStorage.getItem('todo')) || [];
  var maxLength = 0;
  storedArray.forEach(function (item, index, storedArray) {
    if (maxLength < item.length) {
      maxLength = item.length;
      console.log('maxLength: ', maxLength);
    }
  });
  var container = document.querySelector('.container');
  if (inputLength >= maxLength) {
    container.style.width = "".concat(80 + inputLength * 10, "px");
  } else {
    container.style.width = "".concat(80 + maxLength * 10, "px");
  }
  container.style.height = "80 + ".concat((storedArray.length + 1) * 20, "px");
  console.log('storedArray:', storedArray);

  // 입력값을 배열에 추가함
  storedArray.push(inputValue);

  // localStorage에 값을 저장 
  window.localStorage.setItem('todo', JSON.stringify(storedArray));

  // 입력 필드 초기화 
  document.getElementById('inputData').value = '';

  // 배열 화면에 출력
  displayArray(storedArray);
}
function displayArray(array) {
  console.log('displayArray');
  var list = document.getElementById('todoList');
  list.innerHTML = ''; // 기존 리스트 초기화 

  var maxLength = 0;
  for (var i = 0; i < array.length; i++) {
    if (maxLength < array[i].length) {
      maxLength = array[i].length;
      console.log('maxLength: ', maxLength);
    }
  }
  // css에서 클래스 지정하는 함수 
  var container = document.querySelector('.container');

  // 삭제하는 기능

  // 템플릿 리터럴 적용
  container.style.width = "".concat(450 + maxLength * 10, "px");
  container.style.height = "".concat(80 + (array.length + 1) * 20, "px");
  console.log('array:', array);
  array.forEach(function (item, index) {
    // 새로운 리스트 아이템 생성  
    var listItem = document.createElement('li');
    // li를 만들고 이를 참조하는 리스트 생성
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    var label = document.createElement('label');
    label.textContent = item;
    var deleteButton = document.createElement('button');
    deleteButton.type = "button";
    deleteButton.classList.add('deleteButton');
    deleteButton.textContent = 'x';
    deleteButton.addEventListener('click', function () {
      deleteValue(index);
    });
    listItem.appendChild(label);
    listItem.appendChild(checkbox);
    listItem.appendChild(deleteButton);
    // 리스트에 추가 
    list.appendChild(listItem);
  });
}
function deleteValue(index) {
  console.log('hi', index);
  var storedArray = JSON.parse(window.localStorage.getItem('todo')) || [];
  storedArray.splice(index, 1);
  window.localStorage.setItem('todo', JSON.stringify(storedArray));
  displayArray(storedArray);
}

 

 

 

 

 

+ Recent posts