스크립트 로드 순서와 $(document).ready(function(){ } 의 사용을 알 수 있는 코드미러 예제
아래와 같이, <head> 태그 에 스크립트 작성 시 <head> 태그를 모두 읽은 후 <body> 태그의 내용을 읽기 때문에
$(document).ready(function(){ } 안에서 작성해야 <textarea id=“editor”> 태그에 코드미러가 적용됩니다.
<html> <head> // include libraries(jQuery, codemirror) <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/mode/javascript/javascript.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/theme/monokai.min.css"> <script> var cm; $(document).ready(function(){ cm = new CodeMirror.fromTextArea(document.getElementById("editor"), { lineNumbers: true, mode: 'javascript', theme : 'monokai'} ); }); </script> </head> <body> <div> <textarea id="editor"></textarea> </div> </body> </html>
<body> 태그 안에서 <textarea id=“editor”></textarea> 아래에 스크립트를 작성하면
$(document).ready(function(){ } 를 사용하지 않더라도 스크립트가 적용됩니다.
<html> <head> // include libraries(jQuery, codemirror) <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/mode/javascript/javascript.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/theme/monokai.min.css"> </head> <body> <div> <textarea id="editor"></textarea> </div> </body> <script> var cm; cm = new CodeMirror.fromTextArea(document.getElementById("editor"), { lineNumbers: true, mode: 'javascript', theme : 'monokai'} ); </script> </html>