Correct Line Numbers for JavaScript Errors

If you write a good bit of JavaScript on CodePen, you’ve probably thrown a lot of errors. We all do. That’s what coding is: writing a bunch of wrong broken code and then getting it all cleaned up and working. Seeing errors isn’t bad, it’s instructional. Perhaps then you’ve had moments of disappointment when CodePen is showing you that you have a JavaScript error, but it doesn’t seem to show on the correct line in the editor. It’s either on line 1 (because we couldn’t figure it out) or worse, on the completely wrong line.

Now, JavaScript errors are always shown on the exact correct line.

Quick Backstory

CodePen shows you a preview of the code you’re working on in an <iframe>. We process the code you write before it gets put there. We try to be as unobtrusive as possible, but there is some stuff we just gotta do. There are some security-related things, we waggle some things to prevent browser-crashing infinite loops, and we also look for invalid syntax so we can help you with that. After that, we inject all the code into the <iframe> and show it to you.

The document in the iframe was like (simplified for clarity here):

<!DOCTYPE html>
<html lang="en">

<head>

  <style>
    {EDITOR CSS}
  </style>

</head>

<body>

  {EDITOR HTML}

  <script>
    {EDITOR JS}
  </script>

</body>

</html>

That keeps all the code in one document, which is nice for simplicity and performance. But see how the JavaScript you author ends up within an inline <script> block? That makes it hard to know what line of the actual code the error happened on, because it might be on line 568 in that document, but really be the 2nd line of code in the code you author. We tried to do some gymnastics to get the correct line number, and that worked a lot of the time, but sometimes it just didn’t. Not to mention that document isn’t always in that format. For example, when you export a Pen, the CSS and JavaScript are linked up as files because that’s more like how you’d work in real life.

So! rather than an inline <script>, we now use an <script src="your-authored.js">. The result is more like…

<!DOCTYPE html>
<html lang="en">

<head>

  <style>
    {EDITOR CSS}
  </style>

</head>

<body>

  {EDITOR HTML}

  <script src="https://cdpn.io/cp/internal/boomboom/pen.js?key=temp-key"></script>

</body>

</html>

As a separate file, the line numbers for JavaScript errors are always right. And there isn’t much of a performance penalty as the document and the script come from the same connection to the same speedy CDN server which is HTTP/2 enabled.

We might end up doing the same thing for CSS, it’s just CSS doesn’t throw errors in quite the same way so it’s not as pressing.

The post Correct Line Numbers for JavaScript Errors appeared first on CodePen Blog.

CategoriesUncategorized