0

I have the following code in a .html file, and I am then opening it with a browser. Why do I not receive the "Hello World" alert when the page loads? All I see is the "Test" text.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
            $(document).ready(function() {
            alert("Hello World!");
        });
        </script>
    </head>
    <body>
    <p>
        Test
    </p>
    </body>
</html>
EddyJ
  • 117
  • 2
  • 9

4 Answers4

2

You can't declare the [src] attribute and have the contents of a <script> element execute.

You need to use a second <script> element:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        alert("Hello World!");
    });
</script>

NOTE: when using the document.ready callback in jQuery, it's advisable to use the shorthand version to alias jQuery to $ for greater script compatibility:

jQuery(function ($) {
    alert('Hello World');
});
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
1

change it like this

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script>
        $(document).ready(function() {
        alert("Hello World!");
    });
    </script>
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0
<!DOCTYPE html>
<html>
     <head>
         <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
         <script type="text/javascript">           
                $(document).ready(function() {
                    alert("Hello World!");
               });
         </script>
     </head>
     <body>
         <p>Test</p>
     </body>
</html>

With first script tag we LOAD jquery. In second script

BRBT
  • 1,467
  • 8
  • 28
  • 48
3y3skill3r
  • 964
  • 1
  • 11
  • 35
0

As some of the answers already stated, you can't have the browser view the src and the contents through one script tag. Here is the W3C information on it:

The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

http://www.w3.org/TR/html401/interact/scripts.html

Phil
  • 10,948
  • 17
  • 69
  • 101