4

I'm using an html script tag with the src attribute as follows:

<script src="http://...">
</script>

I need to also put a bit more code to redirect the page after the script has run - is it valid/acceptable to add the script between the existing script tags or should I add another script on the end?

This:

<script src="http://...">
    ...do something else he
</script>

Or:

<script src="http://...">
</script>
<script>
    ...my other code here
</script>
dotnetnoob
  • 10,783
  • 20
  • 57
  • 103

4 Answers4

6

No it can't.

Use the bottom one.

The long answer…

w3c states

“The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.

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.”

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

OrderAndChaos
  • 3,547
  • 2
  • 30
  • 57
2

Oh, boy. you can't write code inside the script tag having src tag.

You have to use different script tags.

As js loads top to bottom. Your code will work fine.

Mahavir
  • 322
  • 4
  • 8
2

If a script element has a src attribute, the content must be ignored, any other behaviour is non-conformant.

It has been suggested in blogs (as a hack) to put content in the element knowing that it won't be evaluated, then use DOM methods to get the content as a string and either eval it or insert it in a new script element. Neither of these are a good idea.

So better add another script tag after the initial script tag with the src in it.

0

I've just tried this and the code in between the script tags wont run, I imagine this is because as soon as you add a 'src' attribute the code within the script tags is ignored.

However if you simply want to redirect the page after the script is run you just need

window.location = "../YourRedirectPage";

At the end of the code in the external file

Simeon
  • 797
  • 5
  • 14