How to load ace editor

Ben_hawk picture Ben_hawk · Mar 24, 2013 · Viewed 21.9k times · Source

I am trying to use the Ace code editor library (http://ace.ajax.org/), but im having trouble. According to the embedding guide, this should load the required js files from Amazons CDN.

<script src="http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>

However it fails, in Chromes console it shows:

Could not load worker ace.js:1
DOMException {message: "SecurityError: DOM Exception 18", name: "SecurityError", code: 18, stack: "Error: An attempt was made to break through the se…cloudfront.net/src-min-noconflict/ace.js:1:76296)", INDEX_SIZE_ERR: 1…}
 ace.js:1

I also tried putting the ace library src-min folder locally and loading it with

<script src="/js/ace/ace.js" type="text/javascript" charset="utf-8"></script>

Which also failed with the errors:

Uncaught RangeError: Maximum call stack size exceeded
GET http://mysite/mode-javascript.js 404 (Not Found) 123f2c9_ace_1.js:1
GET http://mysite/notes/theme-monokai.js 404 (Not Found) 123f2c9_ace_1.js:1
Uncaught RangeError: Maximum call stack size exceeded

Lastly I tried loading all the js resources in the ace src-min folder, which also failed with errors :S

Answer

user1467267 picture user1467267 · Mar 24, 2013

I can't paste all the code in the comment, so I'll start to answer your question by updating this one. This works fine for me:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>HTML</title>
    <style>
        #editor { 
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
            }
    </style>
</head>
<body>
    <div id="editor">
        function foo(items) {
            var x = "All this is syntax highlighted";
            return x;
        }
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js" type="text/javascript" charset="utf-8"></script>
    <script>
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.getSession().setMode("ace/mode/javascript");
    </script>
</body>
</html>

Can you test this at your end and see if you still get the problems? If this code (singular) is ok it's probably that some other JavaScript affects ACE.

Here's a JSfiddle: http://jsfiddle.net/yDscY/. I get no errors in my Development Inspector.

I found the problem. If you have PHP or can do it with .htaccess. You have to send specific headers to comply to CORS (Cross Origin Resource Sharing).

access-control-allow-origin: *
access-control-allow-credentials: true

After that it should work.

Update

I didn't test this part thoroughly, but it should work.

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Credentials: "true"
</IfModule>

Good luck!