当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Using HTML script tags to code while they have a source

问题描述:

I noticed that the <script src="..."></script> tag does not allow you to use JavaScript within it, such as:

<script src="myFile.js">

alert( "This is a test" );

</script>

And this does not work, nor does it throw an error in FireBug, why is this happening, why do we have to add extra <script> tags to allow for JS to be used on the form itself?

Example

I have a file, found @ script/addScript.js from my root, and this contains:

function addScript( $src )

{

var script = document.createElement( 'script' );

script.type = "text/javascript";

script.src = $src;

document.getElementsByTagName( 'head' )[0].appendChild( script );

}

This is designed to allow me to add scripts to the DOM quickly and effectively, so I tried to do this:

<script src="script/addScript.js">

addScript( "script/obj.js" );

addScript( "script/home/login.js" );

</script>

But it did not work, so I have to do this instead:

<script>

addScript( "script/obj.js" );

addScript( "script/home/login.js" );

</script>

网友答案:

A script element loads a single script.

It can do that from either a URL or from inline, but it still loads a script so it can't do both.

You you try to do both, the inline script will be ignored:

<script src="example.js">
    this_is_ignored();
</script>

… so you need multiple script elements.

<script src="example.js">
</script>
<script>
    this_is_NOT_ignored();
</script>

It is worth noting that the content of the script element will still exist in the DOM, so some people use it to store data in it which the JS referenced by the src will read. data-* attributes are (arguably) a cleaner approach to that though.

网友答案:

Each <script> element contains one piece of executable javascript code. If you use a src attribute to load an external file, that is the piece of executable js for that element, otherwise it is the code placed between the <script></script> tags. If you try to do both, then you're attempting to associate two pieces of executable code to one script element and that is not the behavior of the script element so the browser's javascript engine ignores the inline code and executes the included file code.

As to why this is the case, it was likely a design choice by whoever established this standard. By creating a one-to-one relationship between code pieces and <javascript> elements there is no ambiguity about what code is being run or its priority.

Therefore in your case you will first have to load your external file...

<script src="script/addScript.js"></script>

and then call any functions provided by it.

<script> addScript( "script/obj.js" ); addScript( "script/home/login.js" ); </script>

For reference, this is generally how all javascript libraries are loaded within a webpage.

分享给朋友:
您可能感兴趣的文章:
随机阅读: