devadam4
devadam4

Reputation: 61

Executing code inside a <script> tag with an external source

Why does this snippet:

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

<script type="text/javascript" src="xxx.js">
</script>

result in "1111" being alerted, but this one:

<script type="text/javascript" src="xxx.js">

alert("111");
</script>

doesn't cause "111" to alert? Is it not possible to put code in the same <script> tag that loads an external script?

Upvotes: 6

Views: 13447

Answers (3)

Paulie Waulie
Paulie Waulie

Reputation: 1690

Your second example is attempting to reference a script from an external file called xxx.js in this case located in the same folder as the html file. If you created that file and placed the alert into that file and moved your script block into the head tag then you would find it would work.

Placing javascript in external files is an encouraged practice because it allows you to reuse common functions in many pages with a simple inlcude statement in your html. Plus it keeps your html files much cleaner.

When you start writing lots of javascript you can combine all your script into one file and then minify it using something like JSMin : http://www.crockford.com/javascript/jsmin.html

This compresses all your script into a tiny form that is unreadable to humans but is much quicker for your sites visitors because it means the script file is smaller and there is only one request to serve the file to the client.

On a side note, another helpful tool when writing javascript is JSLint.

It parses your javascript and informs you of syntax errors and also bad practices.

Happy Coding

Paul

Upvotes: 0

Fyodor Soikin
Fyodor Soikin

Reputation: 80915

Well, this is just how the <script> tag works. If you have a src attribute, the content of the tag gets ignored.

Simply use another <script> tag, what's the problem with that?

Upvotes: 7

cmullins
cmullins

Reputation: 66

The below JavaScript is correct:

<html>
     <head>
          <script type="text/javascript"> alert("1111"); </script>
          <script type="text/javascript" src="xxx.js"> </script>
     </head> 
     <body>
          <p> The actual script is in an external script file called "xxx.js".</p>
     </body>
</html>

If you only want one script tag then put the

 alert("1111");

inside of the xxx.js file.

The alert doesn't work when it is placed in between the script tag with a src because that is the way it is intended to work. It ignores anything between the open and closing script tags when src is specified.

Upvotes: 2

Related Questions