Home >Web Front-end >JS Tutorial >Why is Inline JavaScript Not Working in Script Tags with External Sources?
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.
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.
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>
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!