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
  • 17,780
  • 15
  • 80
  • 114
  • 3
    **This will give you insight** `:)` http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write – Tats_innit Jan 05 '14 at 22:44

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
  • 341,306
  • 83
  • 791
  • 678
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
  • 28,160
  • 11
  • 74
  • 110