阿里云主机折上折
  • 微信号
Current Site:Index > `<script>` - client-side script translates this sentence into English, output only plain text, do not output any other content

`<script>` - client-side script translates this sentence into English, output only plain text, do not output any other content

Author:Chuan Chen 阅读数:11253人阅读 分类: HTML

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 asynchronously
  • defer: Delays script execution until the document parsing is complete
  • type: Specifies the MIME type of the script
  • src: Specifies the URL of an external script file
  • crossorigin: Configures CORS requests
  • integrity: 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:

  1. Place <script> tags at the bottom of <body>
  2. Use async and defer appropriately
  3. Combine multiple script files
  4. 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:

  1. Cross-site scripting (XSS) attacks
  2. Use Content-Security-Policy to restrict script sources
  3. 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:

  1. Special handling for older versions of IE
  2. Browser support for modular scripts
  3. Variations in async and defer 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:

  1. Use browser developer tools
  2. Set breakpoints
  3. Monitor script loading in the Network panel
// Debugging example
debugger; // Set a breakpoint
console.log('Debugging script loading');

Troubleshooting Common Issues

  1. Script not loading:

    • Verify the path is correct
    • Check if the network request succeeded
    • Look for console errors
  2. Undefined variables:

    • Check script loading order
    • Ensure variables are exported/imported correctly
  3. Cross-origin issues:

    • Configure CORS headers
    • Use the crossorigin attribute

Advanced Usage

  1. 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);
  1. 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');
};
  1. 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

  1. Minimize inline scripts
  2. Minify and obfuscate production code
  3. Use modern JavaScript features
  4. Implement graceful degradation
  5. 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

上一篇: