diewland
diewland

Reputation: 1915

Is it possible to execute JavaScript in JavaScript include tag?

Is it possible to do somthing like this ?

<script type='text/javascript' src='xxx.js'>
    alert('Can I say hello in this area?');
</script>

Thanks.

Upvotes: 0

Views: 884

Answers (4)

samshull
samshull

Reputation: 2328

No, but it is possible to do this:


<script type='text/javascript' src='xxx.js'>
    alert('Can I say hello in this area?');
</script>
<script type='text/javascript'>
    eval([].pop.call(document.getElementsByTagName('script')).innerHTML);
</script>

It eval's the .innerHTML of the last script tag that was closed.

It is also possible to include the eval code in your external file, the last script tag should evaluate to the script tag that initialized the file download.

Upvotes: 1

MikeM
MikeM

Reputation: 27405

Nope.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
    var doesItWork = "#myElement";
</script>
<script type="text/javascript">
    $(document).ready(function() {
        alert("did it work?");
        $(doesItWork).text("yes");
    });
</script>

<div id="myElement">no</div>

Upvotes: 1

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

Doesn't work for me in Chrome, Firefox, or Safari so I'm going to say no it's not possible.

Upvotes: 0

Brian Ball
Brian Ball

Reputation: 12596

No, you need to use a separate script, and do not use a self-closing tag, I've wasted many hours figuring out a problem because I used a self-closing script tag.

Use:

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

NOT

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

Upvotes: 0

Related Questions