阿里云主机折上折
  • 微信号
Current Site:Index > `<script>` - client-side script

`<script>` - client-side script

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

The <script> tag is a core element in HTML used for embedding or referencing client-side scripts, typically employed to implement dynamic interactions, data manipulation, or third-party functionality integration. It supports various attributes and loading methods, which directly affect the script's execution timing and behavior.

Basic Syntax of the <script> Tag

The <script> tag has two conventional forms: inline scripts and external scripts. Inline scripts embed code directly within the tag, while external scripts reference external files via the src attribute.

<!-- Inline script example -->
<script>
  console.log('Inline script executed');
</script>

<!-- External script example -->
<script src="app.js"></script>

When the type attribute is not specified, the default value is text/javascript. In modern development, the type is often omitted since JavaScript is the default scripting language.

Key Attributes Explained

src Attribute

Used to reference external script files, which can be absolute or relative paths. For example:

<script src="https://example.com/library.js"></script>
<script src="/local/path/app.js"></script>

async and defer

Control the loading and execution timing of scripts:

  • async: Loads asynchronously and executes immediately after downloading, without guaranteeing order.
    <script async src="script1.js"></script>
    <script async src="script2.js"></script>
    <!-- script2.js may execute before script1.js -->
    
  • defer: Delays execution until after the document is parsed, maintaining order.
    <script defer src="vendor.js"></script>
    <script defer src="app.js"></script>
    <!-- Ensures vendor.js executes before app.js -->
    

Special Values for type

Beyond standard MIME types, modular scripts can also be used:

<script type="module">
  import { utils } from './utils.js';
  console.log(utils.version);
</script>

Script Loading Strategies

Render-Blocking Issues

By default, when the browser encounters a <script> tag, it pauses HTML parsing to execute the script immediately. Placing scripts at the end of <body> minimizes impact:

<body>
  <!-- Page content -->
  <script src="app.js"></script>
</body>

Dynamic Script Loading

Insert scripts dynamically via the DOM API:

const script = document.createElement('script');
script.src = 'dynamic.js';
document.head.appendChild(script);

Practical Use Cases

Data Tracking

Load analytics scripts asynchronously to avoid blocking the main thread:

<script async src="https://analytics.example.com/tracker.js"></script>

Third-Party Library Integration

Use defer to ensure dependency order:

<script defer src="jquery.min.js"></script>
<script defer src="plugin-depends-on-jquery.js"></script>

Performance Optimization Practices

  1. Code Splitting: Load non-critical scripts on demand.
    if (userNeedsFeature) {
      import('./heavy-module.js').then(module => {
        module.init();
      });
    }
    
  2. Lazy Loading with Intersection Observer:
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const script = document.createElement('script');
          script.src = entry.target.dataset.src;
          document.body.appendChild(script);
          observer.unobserve(entry.target);
        }
      });
    });
    observer.observe(document.querySelector('[data-src]'));
    

Security Considerations

Content Security Policy (CSP)

Restrict script sources via HTTP headers:

Content-Security-Policy: script-src 'self' https://trusted.cdn.com

Preventing XSS

Avoid concatenating HTML to insert scripts:

// Dangerous example
document.write(`<script>alert("${userInput}")</script>`);

// Safe approach
const el = document.createElement('div');
el.textContent = userInput;
document.body.appendChild(el);

Compatibility and Modern Practices

Legacy Browser Fallback

Use nomodule to provide fallbacks for browsers that don’t support ES6:

<script type="module" src="modern.js"></script>
<script nomodule src="legacy.js"></script>

Preloading Critical Resources

Load key resources early with <link rel="preload">:

<link rel="preload" href="critical.js" as="script">

Debugging Tips

Source Maps

Debug minified code using sourcemap:

<script src="app.min.js"></script>
<!-- Ensure app.min.js.map exists -->

Error Handling

Globally monitor script errors:

window.addEventListener('error', (e) => {
  console.error('Script load failed:', e.filename);
});

Collaboration with Other Technologies

Working with Web Workers

Offload compute-intensive tasks from the main thread:

// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);

// worker.js
self.onmessage = (e) => {
  const result = heavyComputation(e.data);
  self.postMessage(result);
};

Server-Side Rendering (SSR) Considerations

Avoid duplicate execution of client-side scripts:

<script data-ssr="true">
  window.APP_DATA = JSON.parse('{{serverData|escapejs}}');
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.