2

Below is a neat little snippet of code that makes sure jQuery is succesfully loaded from a CDN or it includes a local copy.

<script>window.jQuery || document.write('<script src="/js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

I get the idea but why does the script tag have two \/ like so: <\/script>?

Is there a special reason that makes that method perferable to the standard way to close the tag?

agconti
  • 16,911
  • 15
  • 76
  • 112

2 Answers2

6

The backslash before / ensures that <\/script> is not interpreted as a closing script tag for the outer script. Without the slash, it would be parsed as:

<script>
window.jQuery || document.write('<script src="/js/vendor/jquery-1.10.2.min.js"></script>
')</script> <!-- where's the starting <script> ? -->

The backslash is used to escape characters inside a string. \/ is treated as /.

(see WHATWG: 4.12.1.2 Restrictions for contents of script elements for more information about this topic)

Rob W
  • 328,606
  • 78
  • 779
  • 666
1

It is a escape character so \/ is equals to /

so final script appended to document if jQuery is not loaded:

<script src="/js/vendor/jquery-1.10.2.min.js"></script>
Zaheer Ahmed
  • 27,470
  • 11
  • 72
  • 109