Class Script<T extends Script<T>>
- All Implemented Interfaces:
HeadElement
- Direct Known Subclasses:
JavaScript,JsonLdScript
<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 Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddSrcCode(String code) Appends JavaScript source code to the script element.protected voidcreate()Hook method called during element creation.setAsync(boolean async) Sets whether the script should be executed asynchronously.setBlocking(String blocking) Sets the blocking attribute indicating that rendering should be blocked until this script is fetched.setCharset(String charset) Deprecated.The charset attribute is obsolete.setCrossOrigin(CrossOrigin crossOrigin) Sets the cross-origin attribute using theCrossOriginenum.setCrossOrigin(String crossOrigin) Sets the crossorigin attribute.setDefer(boolean defer) Sets whether the script should be deferred until the document is parsed.setFetchPriority(String fetchPriority) Sets the fetchpriority attribute.setIntegrity(String integrity) Sets the subresource integrity hash for verifying the fetched script has not been tampered with.setNoModule(boolean noModule) Sets whether the script should not be executed in browsers that support ES modules.Sets the nonce attribute for Content Security Policy.setReferrerPolicy(String referrerPolicy) Sets the referrerpolicy attribute.Sets the URL of an external script file.voidsetSrcCode(String code) Sets the inline JavaScript source code, replacing any existing content.voidsetSrcCodeFromFile(String filename) Sets the script's inline source code to be loaded from a file at render time.Sets the MIME type of the script.Methods inherited from class com.oorian.html.Element
addAttribute, addAttribute, addAttribute, addAttribute, addElement, addLineBreak, addLineOfText, addLineOfText, addLineOfText, addParagraph, addParagraph, addSpacer, addText, addText, addText, addText, assignId, containsElement, containsElement, dispatchEvent, dispatchEvent, dispatchEvent, dispatchEvent, equals, excludeId, executeJs, executeJs, executeJs, getAccept, getAllElements, getAncestor, getAttribute, getAttributes, getComponent, getDir, getElement, getElementById, getElementCount, getElementCount, getElements, getElements, getElementsByComponentName, getElementsByTagName, getHtml, getHtml, getId, getInnerHtml, getInnerHtml, getIs, getItemId, getItemProp, getItemRef, getItemType, getLang, getNextSibling, getPage, getParent, getPart, getPrevSibling, getSlot, getTagName, getTextContent, getUrl, hasAttribute, hasElements, hidden, initialize, insertElement, isChildOf, isClosedTag, isCreated, isDescendantOf, isDescendantOf, isInitialized, isItemScope, isTranslate, onCallback, onCreated, onElementAdded, onElementRemoved, onHashChange, onHidden, onInitialized, onJsReturn, onPageLoaded, onPageUnloaded, onRefresh, onRemovedFromPage, onShown, onUpdated, onUserEvent, prewrite, recreate, refresh, refresh, registerAddition, registerListener, registerListener, registerListener, registerListener, registerListener, registerListener, registerListener, registerSubtraction, registerUpdate, removeAllElements, removeAttribute, removeAttribute, removeElement, removeElement, removeFromParent, requestCallback, requestCallback, requestCallback, requestCallback, resetId, scrollTo, scrollToBottom, scrollToTop, self, sendCommand, sendUpdate, setAccept, setComponent, setDir, setDir, setElement, setId, setIs, setItemId, setItemProp, setItemRef, setItemScope, setItemType, setLang, setOnError, setOnLoad, setPage, setParent, setPart, setSlot, setTagName, setText, setText, setText, setText, setTranslate, shown, toString, unregisterListener, update, updateAttributes
-
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
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
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.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
Sets the cross-origin attribute using theCrossOriginenum.- Parameters:
crossOrigin- The CORS mode.- Returns:
- This element for method chaining.
-
setCrossOrigin
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
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
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
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
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
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
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
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
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
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
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
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:ElementHook 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.
-