Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

embedding jquery.prettyPhoto causes script to show on page

When I move:

<script src="js/jquery.prettyPhoto.js"></script>

To:

<script type="text/javascript">
   ...
</script>

Then the script starts showing on the page from the bold part onwards:

style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true">'},s);var o=this,u=false,a,f,l,c,h,p,d=e(window).height(),v=e...

The script is attributed with this information:

Class: prettyPhoto
Use: Lightbox clone for jQuery
Author: Stephane Caron (http://www.no-margin-for-errors.com)
Version: 3.1.5

How can I move the script from a .js file to the page correctly?

like image 383
Hooli Avatar asked Jun 26 '16 19:06

Hooli


1 Answers

When the content of a javascript contains the closing script tag </script> it can cause the browser's parser to interpret wrongly the script block code.

The code here:

<script type="text/javascript">
    alert("</script>");
</script>

Will not work and the output you will see in the browser will be

");

As if the browser read the script block as

**script start tag ->** <script type="text/javascript">
    alert("</script> **<- script end tag**

The Solution

There are two known solutions for having the <script>...</script> string inside a script block:

  1. Break the string into two separate string and concatenate them using +

<script type="text/javascript">
    alert("<scr"+"ipt>...</scr"+ "ipt>");
</script>
  1. Wrap the whole script code block with comment block code:

    <script type="text/javascript">
        <!--
        alert("<script></script>");
        -->
    </script>

Note that the second example will NOT WORK if you only have the closing-tag, since the browser will tag that closing string as the tag that was supposed to close your original opening <scrip> tag.

This example will not work:

    <script type="text/javascript">
        <!--
        alert("</script>");
        -->
    </script>

Specifically for your code - this is the jsfiddle that fixes it.

like image 79
Dekel Avatar answered Oct 05 '22 23:10

Dekel