Home >Web Front-end >JS Tutorial >Why is Inline JavaScript Not Working in Script Tags with External Sources?

Why is Inline JavaScript Not Working in Script Tags with External Sources?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 03:38:31246browse

Why is Inline JavaScript Not Working in Script Tags with External Sources?

Loading Scripts with HTML Script Tags

The HTML script tag is used to include and execute JavaScript code. By default, this tag takes an external source attribute, such as scr to load a JavaScript file. However, attempts to include inline JavaScript within the script tag, like this:

<script src="myFile.js">
    alert( "This is a test" );
</script>

Fail silently without throwing errors.

Why Using Inline JavaScript in Script Tag Doesn't Work

The reason for this behavior is that a script element can only load a single source, be it external or inline. When both src and inline content are present, the inline content is ignored. Therefore:

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

Will not load the specified scripts.

Solution: Using Multiple Script Elements

To load multiple scripts, you need to use separate script elements for each:

<script src="script/obj.js"></script>
<script src="script/home/login.js"></script>

Alternatively, you can create a parent script that dynamically loads the necessary scripts:

<script>
var scripts = ["script/obj.js", "script/home/login.js"];
for (var i = 0; i < scripts.length; i++) {
  var script = document.createElement("script");
  script.src = scripts[i];
  document.head.appendChild(script);
}
</script>

Additional Notes

While inline JavaScript is ignored in script elements with external sources, the content of the script element remains in the DOM. This has prompted some developers to use it for storing data that is accessed by the external scripts. However, using data-* attributes is generally a more appropriate and cleaner approach for this purpose.

The above is the detailed content of Why is Inline JavaScript Not Working in Script Tags with External Sources?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn