`<script>` - client-side script translates this sentence into English, output only plain text, do not output any other content
Basic Syntax of the <script>
Tag
The <script>
tag is used to embed or reference client-side script code, typically JavaScript, in an HTML document. The basic syntax is as follows:
<script>
// JavaScript code goes here
console.log('Hello, World!');
</script>
Alternatively, you can reference an external script file using the src
attribute:
<script src="script.js"></script>
Attributes of the <script>
Tag
The <script>
tag supports multiple attributes to control script loading and execution behavior:
async
: Instructs the browser to load the script asynchronouslydefer
: Delays script execution until the document parsing is completetype
: Specifies the MIME type of the scriptsrc
: Specifies the URL of an external script filecrossorigin
: Configures CORS requestsintegrity
: Used for subresource integrity verification
<script src="app.js" async defer crossorigin="anonymous" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"></script>
Script Loading and Execution Order
When the browser encounters a <script>
tag while parsing an HTML document, it pauses document parsing, downloads and executes the script, and then resumes parsing. This behavior can be altered using the async
and defer
attributes:
<!-- Default behavior: blocks parsing -->
<script src="blocking.js"></script>
<!-- Async loading: does not block parsing, executes immediately after download -->
<script src="async.js" async></script>
<!-- Deferred execution: does not block parsing, executes after document parsing is complete -->
<script src="defer.js" defer></script>
Inline Scripts vs. External Scripts
Inline scripts are written directly in the HTML file:
<script>
function showAlert() {
alert('Button clicked!');
}
</script>
<button onclick="showAlert()">Click me</button>
External scripts are stored in separate files and referenced via src
:
<script src="scripts/main.js"></script>
Advantages of external scripts:
- Can be cached by the browser
- Easier to maintain
- Can be shared across multiple pages
Dynamic Script Loading
JavaScript can dynamically create and insert <script>
elements:
function loadScript(url, callback) {
const script = document.createElement('script');
script.src = url;
script.onload = callback;
document.head.appendChild(script);
}
loadScript('dynamic.js', function() {
console.log('Script loaded!');
});
Modular Scripts
Modern JavaScript supports modularity, allowing the use of ES6 modules via the type="module"
attribute:
<script type="module">
import { greet } from './greetings.js';
greet('World');
</script>
Module scripts inherently behave like defer
and support cross-origin requests.
Event Handling
The <script>
element supports various events:
const script = document.createElement('script');
script.onload = function() {
console.log('Script loaded successfully');
};
script.onerror = function() {
console.error('Script loading failed');
};
script.src = 'some-script.js';
document.head.appendChild(script);
Performance Optimization Considerations
Script loading significantly impacts page performance:
- Place
<script>
tags at the bottom of<body>
- Use
async
anddefer
appropriately - Combine multiple script files
- Use code splitting and lazy loading
<!-- Performance optimization example -->
<script src="critical.js" defer></script>
<script src="non-critical.js" async></script>
Security Considerations
When using the <script>
tag, be aware of security risks:
- Cross-site scripting (XSS) attacks
- Use
Content-Security-Policy
to restrict script sources - Verify the integrity of external scripts
<!-- Use SRI to verify script integrity -->
<script src="https://example.com/example-framework.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
Compatibility Considerations
Different browsers implement the <script>
tag differently:
- Special handling for older versions of IE
- Browser support for modular scripts
- Variations in
async
anddefer
implementations
<!-- Conditional comments for IE-specific scripts -->
<!--[if IE]>
<script src="ie-specific.js"></script>
<![endif]-->
Usage in Modern JavaScript Frameworks
Modern frontend frameworks typically have their own ways of handling scripts:
React example:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return <h1>Hello, World!</h1>;
}
ReactDOM.render(<App />, document.getElementById('root'));
Vue example:
new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
Debugging Tips
Debugging code loaded via <script>
tags:
- Use browser developer tools
- Set breakpoints
- Monitor script loading in the Network panel
// Debugging example
debugger; // Set a breakpoint
console.log('Debugging script loading');
Troubleshooting Common Issues
-
Script not loading:
- Verify the path is correct
- Check if the network request succeeded
- Look for console errors
-
Undefined variables:
- Check script loading order
- Ensure variables are exported/imported correctly
-
Cross-origin issues:
- Configure CORS headers
- Use the
crossorigin
attribute
Advanced Usage
- JSONP technique:
function handleResponse(data) {
console.log(data);
}
const script = document.createElement('script');
script.src = 'https://api.example.com/data?callback=handleResponse';
document.head.appendChild(script);
- Web Worker:
// main.js
const worker = new Worker('worker.js');
worker.postMessage('Hello Worker');
worker.onmessage = function(e) {
console.log('Message from worker:', e.data);
};
// worker.js
self.onmessage = function(e) {
console.log('Message from main:', e.data);
self.postMessage('Hello Main');
};
- Service Worker:
// Register Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('ServiceWorker registration successful');
})
.catch(err => {
console.log('ServiceWorker registration failed: ', err);
});
}
Performance Monitoring
Monitor script loading performance:
// Use Performance API
const [entry] = performance.getEntriesByName('https://example.com/script.js');
console.log('Script load time:', entry.duration);
Best Practices
- Minimize inline scripts
- Minify and obfuscate production code
- Use modern JavaScript features
- Implement graceful degradation
- Consider accessibility
<!-- Graceful degradation example -->
<script>
// Modern feature detection
if ('Promise' in window) {
// Use modern code
import('./modern-app.js');
} else {
// Fallback solution
document.write('<script src="legacy-app.js"><\/script>');
}
</script>
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn