Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 623
devadam4 Avatar asked Aug 26 '10 21:08

devadam4


2 Answers

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?

like image 105
Fyodor Soikin Avatar answered Oct 06 '22 18:10

Fyodor Soikin


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.

like image 40
cmullins Avatar answered Oct 06 '22 20:10

cmullins