ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • reading-tine.js 읽는시간 표시
    Coding 2022. 6. 6. 17:05

    개요

    최근에는 뉴스나 블로그에 많이 사용되는 reading time 라이브러리에 대해서 활용해보고자 합니다. 보통 글의 header 부분의 제목 에 article을 읽는데 대략 어느 정도가 걸리는지 알려줘 결정에 도움을 줄 수 있게 안내하는 기능입니다.

    읽는 시간 모습

    이런식으로 읽는데 얼마나 걸리는지 가늠할 수 있게 표시해줌

    블로그에 도입해보고자 기능을 확인하고 익혀봅니다.

     

    공식 깃허브 : https://github.com/michael-lynch/reading-time 

     

    GitHub - michael-lynch/reading-time: A simple, lightweight jQuery plugin used to display an estimated time to read some text.

    A simple, lightweight jQuery plugin used to display an estimated time to read some text. - GitHub - michael-lynch/reading-time: A simple, lightweight jQuery plugin used to display an estimated time...

    github.com

    소개

    jQuery와 plugin을 page의 head 혹은 footer에 포함시켜야한다.

    element 만들기

    읽는데 소요되는 예상 시간이 보여질 element를 만드는데 class 이름은 eta라고 함

    또한 총 단어 갯수를 보여주고 싶다면 아무 class나 ID로 하나 더 만들어 해볼 수 있다 함

    예시

    총 단어 갯수를 보여줄 word-count요소도 만든다면 이런식으로 만들 수 있음

    target이 될 요소를 대상으로 .readingTime()함수를 호출

    이렇게 하면 끝이남

    이런 내용만으로 작동하는지 테스트

    <html>
    <head>
        <meta charset="UTF-8">
        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/reading-time/2.0.0/readingTime.js" integrity="sha512-YWeIytX1fEAyaUgR1iSJgoYrWKxZH/I8XmviT/MqvZUPCabDslO7tyZOwdpJ0kNZBU1hwOQ1lTbEEcmK2jtghQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </head>
    <body>
        <article>
               <div>
                Earlier this year, the concentration of carbon dioxide in the atmosphere reached 400 parts per million (ppm). The last time there was that much CO2 in our atmosphere was three million years ago, when sea levels were 24 meters higher than they are today. Now sea levels are rising again. Last September, Arctic sea ice covered the smallest area ever recorded. All but one of the ten warmest years since 1880, when global records began to be kept, have occurred in the twenty-first century.
     
                Some climate scientists believe that 400 ppm of CO2 in the atmosphere is already enough to take us past the tipping point at which we risk a climate catastrophe that will turn billions of people into refugees. They say that we need to get the amount of atmospheric CO2 back down to 350 ppm. That figure lies behind the name taken by 350.org, a grassroots movement with volunteers in 188 countries trying to solve the problem of climate change.
     
                Other climate scientists are more optimistic: they argue that if we allow atmospheric CO2 to rise to 450 ppm, a level associated with a two-degree Celsius temperature rise, we have a 66.6% chance of avoiding catastrophe. That still leaves a one-in-three chance of catastrophe – worse odds than playing Russian roulette. And we are forecast to surpass 450 ppm by 2038.
     
                One thing is clear: if we are not to be totally reckless with our planet’s climate, we cannot burn all the coal, oil, and natural gas that we have already located. About 80% of it – especially the coal, which emits the most CO2 when burned – will have to stay in the ground.
     
                In June, US President Barack Obama told students at Georgetown University that he refused to condemn them and their children and grandchildren to “a planet that’s beyond fixing.” Saying that climate change cannot wait for Congress to overcome its “partisan gridlock,” he announced measures using his executive power to limit CO2 emissions, first from new fossil-fuel power plants, and then from existing ones.
     
                Obama also called for an end to public financing of new coal plants overseas, unless they deploy carbon-capture technologies (which are not yet economically viable), or else there is, he said, “no other viable way for the poorest countries to generate electricity.”
     
                According to Daniel Schrag, Director of Harvard University’s Center for the Environment and a member of a presidential science panel that has helped to advise Obama on climate change, “Politically, the White House is hesitant to say they’re having a war on coal. On the other hand, a war on coal is exactly what’s needed.”
     
                Schrag is right. His university, like mine and many others, has a plan to reduce its greenhouse-gas emissions. Yet most of them, including Schrag’s and mine, continue to invest part of their multi-billion-dollar endowments in companies that extract and sell coal.
     
                But pressure on educational institutions to stop investing in fossil fuels is beginning to build. Student groups have formed on many campuses, and a handful of colleges and universities have already pledged to end their investment in fossil fuels. Several US cities, including San Francisco and Seattle, have agreed to do the same.
     
                Now financial institutions, too, are coming under fire for their involvement with fossil fuels. In June, I was part of a group of prominent Australians who signed an open letter to the heads of the country’s biggest banks asking them to stop lending to new fossil-fuel extraction projects, and to sell their stakes in companies engaged in such activities.
     
                Speaking at Harvard earlier this year, former US Vice President Al Gore praised a student group that was pushing the university to sell its investments in fossil-fuel companies, and compared their activities to the divestment campaign in the 1980’s that helped to end South Africa’s racist apartheid policy.
     
                How fair is that comparison? The dividing lines may be less sharp than they were with apartheid, but our continued high level of greenhouse-gas emissions protects the interests of one group of humans – mainly affluent people who are alive today – at the cost of others. (Compared to most of the world’s population, even the American and Australian coal miners who would lose their jobs if the industry shut down are affluent.) Our behavior disregards most of the world’s poor, and everyone who will live on this planet in centuries to come.
               </div>
            </div>
        </article>
        <br /><br />
        <div class="eta"></div>
        <script>
            $('article').readingTime();
        </script>
    </body>
    </html>

    이 코드를 html파일로 만들고 브라우저에 띄워보면

    html 파일로 만들고 브라우저에 뛰운 모습

    aticle을 분석해 3분 소요될것이라고 알려주는데 이 글이 3분인지는 잘 모르겠으나 이렇다함

     

    한국인 개발자분이 풀 리퀘스트해주신 한국어 버전을 활용해보겠습니다. reading-time.js 링크

    https://raw.githubusercontent.com/Shane-Park/markdownBlog/master/frontend/jsLibrary/readingtime/readingtime.js

     

    같은 폴더에 readingtime.js와 style.css 파일을 넣은 모습

    html파일에 css와 js 파일을 새로 첨부

    	 <link rel="stylesheet" href="./style.css">
        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="./readingtime.js"></script>
    <html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="./style.css">
        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="./readingtime.js"></script>
    </head>
    <body>
        <div class="eta"></div>
        <article>
               <div>
                Earlier this year, the concentration of carbon dioxide in the atmosphere reached 400 parts per million (ppm). The last time there was that much CO2 in our atmosphere was three million years ago, when sea levels were 24 meters higher than they are today. Now sea levels are rising again. Last September, Arctic sea ice covered the smallest area ever recorded. All but one of the ten warmest years since 1880, when global records began to be kept, have occurred in the twenty-first century.
     
                Some climate scientists believe that 400 ppm of CO2 in the atmosphere is already enough to take us past the tipping point at which we risk a climate catastrophe that will turn billions of people into refugees. They say that we need to get the amount of atmospheric CO2 back down to 350 ppm. That figure lies behind the name taken by 350.org, a grassroots movement with volunteers in 188 countries trying to solve the problem of climate change.
     
                Other climate scientists are more optimistic: they argue that if we allow atmospheric CO2 to rise to 450 ppm, a level associated with a two-degree Celsius temperature rise, we have a 66.6% chance of avoiding catastrophe. That still leaves a one-in-three chance of catastrophe – worse odds than playing Russian roulette. And we are forecast to surpass 450 ppm by 2038.
     
                One thing is clear: if we are not to be totally reckless with our planet’s climate, we cannot burn all the coal, oil, and natural gas that we have already located. About 80% of it – especially the coal, which emits the most CO2 when burned – will have to stay in the ground.
     
                In June, US President Barack Obama told students at Georgetown University that he refused to condemn them and their children and grandchildren to “a planet that’s beyond fixing.” Saying that climate change cannot wait for Congress to overcome its “partisan gridlock,” he announced measures using his executive power to limit CO2 emissions, first from new fossil-fuel power plants, and then from existing ones.
     
                Obama also called for an end to public financing of new coal plants overseas, unless they deploy carbon-capture technologies (which are not yet economically viable), or else there is, he said, “no other viable way for the poorest countries to generate electricity.”
     
                According to Daniel Schrag, Director of Harvard University’s Center for the Environment and a member of a presidential science panel that has helped to advise Obama on climate change, “Politically, the White House is hesitant to say they’re having a war on coal. On the other hand, a war on coal is exactly what’s needed.”
     
                Schrag is right. His university, like mine and many others, has a plan to reduce its greenhouse-gas emissions. Yet most of them, including Schrag’s and mine, continue to invest part of their multi-billion-dollar endowments in companies that extract and sell coal.
     
                But pressure on educational institutions to stop investing in fossil fuels is beginning to build. Student groups have formed on many campuses, and a handful of colleges and universities have already pledged to end their investment in fossil fuels. Several US cities, including San Francisco and Seattle, have agreed to do the same.
     
                Now financial institutions, too, are coming under fire for their involvement with fossil fuels. In June, I was part of a group of prominent Australians who signed an open letter to the heads of the country’s biggest banks asking them to stop lending to new fossil-fuel extraction projects, and to sell their stakes in companies engaged in such activities.
     
                Speaking at Harvard earlier this year, former US Vice President Al Gore praised a student group that was pushing the university to sell its investments in fossil-fuel companies, and compared their activities to the divestment campaign in the 1980’s that helped to end South Africa’s racist apartheid policy.
     
                How fair is that comparison? The dividing lines may be less sharp than they were with apartheid, but our continued high level of greenhouse-gas emissions protects the interests of one group of humans – mainly affluent people who are alive today – at the cost of others. (Compared to most of the world’s population, even the American and Australian coal miners who would lose their jobs if the industry shut down are affluent.) Our behavior disregards most of the world’s poor, and everyone who will live on this planet in centuries to come.
               </div>
            </div>
        </article>
        <br /><br />
        <script>
            $('article').readingTime();
        </script>
    </body>
    </html>

    실행

    수정하여 실행해본 모습

    .readingTime()로 간단하게 실행 했지만 몇가지 옵션을 활용해서 추가적으로 커스텀해볼 수 있겠습니다.

     

    옵션

    • readingTimeAsNumber: boolean
      If you want to take reading time as integer, you can use this (default: 'false').

    "읽는 시간을 number로 받을지에 대한 옵션. 기본값은 false"

     

    • readingTimeTarget: "id / class / element"
      A string that defines the ID, class or element that will store the estimated reading time (default: 'eta').

    "읽는 시간을 표시할 요소 선택, 따로 입력하지 않으면 기본값 eta"

     

    • wordCountTarget: "id / class / element"
      A string that defines the ID, class or element that will store the total word count (default: '').

    "전체 단어 수를 세서 표시할 요소를 선택"

     

    • remotePath: "path"
      A string that indicates the path to the remote file (default: null).

    "읽어서 분석할 문장이 html 요소가 아닌 외부 파일일 경우 그 경로를 설정함"

     

    • remoteTarget: "id / class / element"
      A string that defines the ID, class or element in the remote file that contains the text in which you want to estimate the reading time of (default: null).

    "외부 파일의 경로가 아닌 요소로서 접근할 때 사용함"

     

    • wordsPerMinute: integer
      An integer that defines the words per minute at which to calculate the estimated reading time (default: 270).

    "분당 몇 단어를 읽는지 읽는 속도를 정함, 따로 정해주지 않으면 분당 270개로 계산"

     

    • round: boolean
      A boolean value that indicates whether or not the estimated reading time should be rounded to the closest minute (default: true).

    "반올림을 할 지에 대한 설정으로 읽는데 2분 40초가 걸린다 할때 round:true로 되있으면 분으로 나오면 false의 경우 2:40로 표기됨"

     

    • lang: "en / fr / de / es / nl / sk / cz / ru / zh / kr"
      A two letter string that indicates the language to be used (default: "en").

    "사용할 언어를 선택함"

     

    • lessThanAMinuteString: string
      A string that changes the default "Less than a minute" copy (default: '').

    "1분보다 적을 경우 뭐라고 표시해줄지 설정할 수 있음. 따로 설정하지 않으면 각 언어별 기본 설정을 따라감"

     

    1분이하시 모습
    한국말로 변경후 모습, (우측)언어수정

    • prependTimeString: string
      A string that is prepended before the estimated reading time (default: '').

    "시간 앞에 미리 붙일 말을 쓸 수 있음"

     

    • prependWordString: string
      A string that is prepended before the total word count (default: '').

    "총 단어 갯수 앞에도 쓸 말을 설정 할 수 있음"

     

    • success: function(data) {}
      A callback function that runs if the plugin was successful (default: function()).
    • error: function(data) {}
      A callback function that runs if the plugin fails (default: function(message)).

    "각각 성공/실패시의 callback function"

     

    옵션을 토대로 html에 javascript 수정

    수정한 부분 모습

    그결과

    수정한 모습

    이를 활용해 블로그에 적용시켜볼 수 있습니다.

     

Designed by Tistory.