Class Script<T extends Script<T>>

java.lang.Object
com.oorian.html.Element<T>
com.oorian.html.elements.Script<T>
All Implemented Interfaces:
HeadElement
Direct Known Subclasses:
JavaScript, JsonLdScript

public class Script<T extends Script<T>> extends Element<T> implements HeadElement
Represents an HTML <script> element that embeds or references executable JavaScript code.

The <script> element is used to embed client-side scripts (typically JavaScript) or reference external script files. Scripts can be executed immediately, deferred until the document is parsed, or loaded asynchronously. This element is essential for adding interactive functionality to web pages.

Features:

  • Embeds inline JavaScript code
  • References external JavaScript files via src attribute
  • Loads inline source code from a file at render time
  • Supports async and defer loading strategies
  • Configurable script type and character encoding
  • ID attribute excluded by default

Usage:


 // External script reference
 Script jquery = new Script();
 jquery.setSrc("https://code.jquery.com/jquery-3.6.0.min.js");

 // External script with async loading
 Script analytics = new Script();
 analytics.setSrc("/js/analytics.js");
 analytics.setAsync(true);

 // External script with deferred execution
 Script app = new Script();
 app.setSrc("/js/app.js");
 app.setDefer(true);

 // Inline JavaScript code
 Script inline = new Script();
 inline.setSrcCode("console.log('Hello, World!');");

 // Multiple lines of inline code
 Script multiLine = new Script();
 multiLine.addSrcCode("function greet(name) {\n");
 multiLine.addSrcCode("    console.log('Hello, ' + name);\n");
 multiLine.addSrcCode("}\n");
 multiLine.addSrcCode("greet('User');");

 // Inline code loaded from a file at render time
 Script fromFile = new Script();
 fromFile.setSrcCodeFromFile("/js/my-logic.js");

 // Script with specific type
 Script module = new Script();
 module.setType("module");
 module.setSrc("/js/main.mjs");
 
Since:
2007
Version:
1.0
Author:
Marvin P. Warble Jr.
See Also:
  • Constructor Details

    • Script

      public Script()
      Constructs a new Script element.

      Creates an HTML <script> element with ID attribute excluded. The script can contain inline code or reference an external file.

  • Method Details

    • setAsync

      public T setAsync(boolean async)
      Sets whether the script should be executed asynchronously.

      The async attribute indicates that the script should be downloaded in parallel to parsing the page and executed as soon as it's available. This only applies to external scripts (with src attribute). Async scripts don't block page rendering but may execute in any order.

      Parameters:
      async - true to load the script asynchronously, false otherwise.
      Returns:
      this element for method chaining
    • setBlocking

      public T setBlocking(String blocking)
      Sets the blocking attribute indicating that rendering should be blocked until this script is fetched.

      The value "render" prevents the browser from rendering content until the script is loaded.

      Parameters:
      blocking - The blocking token(s).
      Returns:
      This element for method chaining.
    • setCharset

      @Deprecated public T setCharset(String charset)
      Deprecated.
      The charset attribute is obsolete. Use UTF-8 encoding for scripts.
      Sets the character encoding of the external script.

      The charset attribute specifies the character encoding used in the external script file. Common values include "UTF-8", "ISO-8859-1", etc. This attribute is only applicable for external scripts.

      Parameters:
      charset - the character encoding (e.g., "UTF-8").
      Returns:
      this element for method chaining
    • setCrossOrigin

      public T setCrossOrigin(CrossOrigin crossOrigin)
      Sets the cross-origin attribute using the CrossOrigin enum.
      Parameters:
      crossOrigin - The CORS mode.
      Returns:
      This element for method chaining.
    • setCrossOrigin

      public T setCrossOrigin(String crossOrigin)
      Sets the crossorigin attribute.

      Specifies how the element handles cross-origin requests. The value "anonymous" sends requests without credentials; "use-credentials" includes cookies and authentication.

      Parameters:
      crossOrigin - The cross-origin value (anonymous, use-credentials).
      Returns:
      This element for method chaining.
    • setDefer

      public T setDefer(boolean defer)
      Sets whether the script should be deferred until the document is parsed.

      The defer attribute indicates that the script should be executed after the document has been parsed but before firing DOMContentLoaded. This only applies to external scripts (with src attribute). Deferred scripts execute in document order.

      Parameters:
      defer - true to defer script execution, false otherwise
      Returns:
      this element for method chaining
    • setFetchPriority

      public T setFetchPriority(String fetchPriority)
      Sets the fetchpriority attribute.

      Provides a hint to the browser about the relative priority of fetching this script. Values include "high", "low", and "auto" (default).

      Parameters:
      fetchPriority - The fetch priority (high, low, auto).
      Returns:
      This element for method chaining.
    • setIntegrity

      public T setIntegrity(String integrity)
      Sets the subresource integrity hash for verifying the fetched script has not been tampered with.

      The browser verifies the fetched resource matches the hash before executing it, protecting against CDN tampering.

      Parameters:
      integrity - The subresource integrity hash.
      Returns:
      This element for method chaining.
    • setNoModule

      public T setNoModule(boolean noModule)
      Sets whether the script should not be executed in browsers that support ES modules.

      The nomodule attribute is used to provide fallback scripts for browsers that do not support JavaScript modules. Browsers that support type="module" will ignore scripts with this attribute.

      Parameters:
      noModule - true to mark as a nomodule fallback script, false otherwise
      Returns:
      this element for method chaining
    • setNonce

      public T setNonce(String nonce)
      Sets the nonce attribute for Content Security Policy.

      A cryptographic nonce used by Content Security Policy to determine whether a given script will be allowed to execute.

      Parameters:
      nonce - The nonce value.
      Returns:
      This element for method chaining.
    • setReferrerPolicy

      public T setReferrerPolicy(String referrerPolicy)
      Sets the referrerpolicy attribute.

      Specifies how much referrer information to send when fetching this script. Common values include "no-referrer", "origin", and "strict-origin-when-cross-origin".

      Parameters:
      referrerPolicy - The referrer policy value.
      Returns:
      This element for method chaining.
    • setSrc

      public T setSrc(String url)
      Sets the URL of an external script file.

      The src attribute specifies the URL of the external JavaScript file to load. When this attribute is set, any inline content in the script element is ignored. Can be an absolute or relative URL.

      If the URL starts with "/" (absolute path within the application), the servlet context path will be automatically prepended.

      Parameters:
      url - the URL of the external script file.
    • setSrcCode

      public void setSrcCode(String code)
      Sets the inline JavaScript source code, replacing any existing content.

      Removes all existing content and sets the script content to the specified source code. This also clears any pending file load set by setSrcCodeFromFile(String).

      Parameters:
      code - the JavaScript source code to embed.
    • setSrcCodeFromFile

      public void setSrcCodeFromFile(String filename)
      Sets the script's inline source code to be loaded from a file at render time.

      The file is read from the servlet context during the create() phase, just before the page is rendered. This allows loading JavaScript source code from a file without having to embed it as a Java string literal. Any existing inline content is cleared.

      The filename should be a path relative to the web application root (e.g., "/js/my-logic.js").

      Parameters:
      filename - the path to the JavaScript file within the web application.
    • setType

      public T setType(String mediaType)
      Sets the MIME type of the script.

      The type attribute specifies the scripting language MIME type. Common values include "text/javascript" (default), "module" for ES6 modules, or custom types. Modern browsers assume JavaScript by default, so this is often omitted.

      Parameters:
      mediaType - the MIME type (e.g., "text/javascript", "module").
    • addSrcCode

      public void addSrcCode(String code)
      Appends JavaScript source code to the script element.

      Appends the specified code to the script's content. This allows building script content incrementally. Multiple calls will concatenate the code.

      Note: JavaScript code is output without HTML escaping since it is trusted developer content, not user input. Never pass unsanitized user input to this method.

      Parameters:
      code - the JavaScript source code to append.
    • create

      protected void create()
      Description copied from class: Element
      Hook method called during element creation.

      Override this method to configure the element after initialization. This is called after Element.initialize() and only once during the element's lifecycle.

      Overrides:
      create in class Element<T extends Script<T>>