Javascript new script element

How to dynamically load a JS file in JavaScript

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Typically, we load a JavaScript file using the script tag:

Dynamic loading

In some situations, we want to load third-party script files like Google Analytics and Google Ads dynamically in JavaScript.

Those files can be loaded asynchronously in JavaScript.

To load a JavaScript file dynamically:

  • Create a script element.
  • Set the src , async , and type attributes.
  • Append the script element to the body.
  • Check if the file loaded or not in the load event.

Create a script element

let scriptEle = document.createElement("script"); 

Set the src , async , and type attributes.

  • src : the file path
  • type : file type — «text/javascript»
  • async : if we set async to false , then the file will be loaded and executed first before proceeding to the next action.
scriptEle.setAttribute("src", "https://www.mywebsite.com/test.js"); 

Append the script element to the body

document.body.appendChild(scriptEle); 

Check the load event

scriptEle.addEventListener("load", () => < console.log("File loaded") >); scriptEle.addEventListener("error", (ev) => < console.log("Error on loading file", ev); >); 

Let’s combine all the pieces

function loadJS(FILE_URL, async = true) < let scriptEle = document.createElement("script"); scriptEle.setAttribute("src", FILE_URL); scriptEle.setAttribute("type", "text/javascript"); scriptEle.setAttribute("async", async); document.body.appendChild(scriptEle); // success event scriptEle.addEventListener("load", () =>< console.log("File loaded") >); // error event scriptEle.addEventListener("error", (ev) => < console.log("Error on loading file", ev); >); > loadJS("file1_path", true); // If we set async false, file2 is loaded and executed first, then file3 will be loaded loadJS("file2_path", false); loadJS("file3_path", true); 

Using Promise to load the script file

const loadScript = (FILE_URL, async = true, type = "text/javascript") => < return new Promise((resolve, reject) => < try < const scriptEle = document.createElement("script"); scriptEle.type = type; scriptEle.async = async; scriptEle.src =FILE_URL; scriptEle.addEventListener("load", (ev) =>< resolve(< status: true >); >); scriptEle.addEventListener("error", (ev) => < reject(< status: false, message: `Failed to load the script $` >); >); document.body.appendChild(scriptEle); > catch (error) < reject(error); >>); >; loadScript("file1_url") .then( data => < console.log("Script loaded successfully", data); >) .catch( err => < console.error(err); >); 

Источник

Читайте также:  Java class newinstance deprecated

HTMLScriptElement

JavaScript files should be served with the application/javascript MIME type, but browsers are lenient and block them only if the script is served with an image type ( image/* ), video type ( video/* ), audio type ( audio/* ), or text/csv . If the script is blocked, its element receives an error event; otherwise, it receives a load event.

Instance properties

  1. If the async attribute is present, then the script will be executed asynchronously as soon as it downloads.
  2. If the async attribute is absent but the defer attribute is present, then the script is executed when the page has finished parsing.
  3. If neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page.

The defer attribute may be specified with the async attribute, so legacy browsers that only support defer (and not async ) fall back to the defer behavior instead of the default blocking behavior.

Note: The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. These algorithms describe the core ideas, but they rely on the parsing rules for start and end tags in HTML, in foreign content, and in XML; the rules for the document.write() method; the handling of scripting; and so on.

A string reflecting the CORS setting for the script element. For scripts from other origins, this controls if error information will be exposed.

An optional string representing a hint given to the browser on how it should prioritize fetching of an external script relative to other external scripts. If this value is provided, it must be one of the possible permitted values: high to fetch at a high priority, low to fetch at a low priority, or auto to indicate no preference (which is the default).

A boolean value that if true, stops the script’s execution in browsers that support ES modules — used to run fallback scripts in older browsers that do not support JavaScript modules.

Читайте также:  Absolute and relative url in java

A string that reflects the referrerPolicy HTML attribute indicating which referrer to use when fetching the script, and fetches done by that script.

Static methods

Returns true if the browser supports scripts of the specified type and false otherwise. This method provides a simple and unified method for script-related feature detection.

Instance methods

No specific methods; inherits methods from its parent, HTMLElement .

Events

No specific events; inherits events from its parent, HTMLElement .

Examples

Dynamically importing scripts

Let’s create a function that imports new scripts within a document creating a node immediately before the that hosts the following code (through document.currentScript ). These scripts will be asynchronously executed. For more details, see the defer and async properties.

function loadError(oError)  throw new URIError(`The script $oError.target.src> didn't load correctly.`); > function prefixScript(url, onloadFunction)  const newScript = document.createElement("script"); newScript.onerror = loadError; if (onloadFunction)  newScript.onload = onloadFunction; > document.currentScript.parentNode.insertBefore( newScript, document.currentScript, ); newScript.src = url; > 

This next function, instead of prepending the new scripts immediately before the document.currentScript element, appends them as children of the tag.

function loadError(oError)  throw new URIError(`The script $oError.target.src> didn't load correctly.`); > function affixScriptToHead(url, onloadFunction)  const newScript = document.createElement("script"); newScript.onerror = loadError; if (onloadFunction)  newScript.onload = onloadFunction; > document.head.appendChild(newScript); newScript.src = url; > 
affixScriptToHead("myScript1.js"); affixScriptToHead("myScript2.js", () =>  alert('The script "myScript2.js" has been correctly loaded.'); >); 

Checking if a script type is supported

HTMLScriptElement.supports() provides a unified mechanism for checking whether a browser supports particular types of scripts.

The example below shows how to check for module support, using the existence of the noModule attribute as a fallback.

function checkModuleSupport()  if ("supports" in HTMLScriptElement)  return HTMLScriptElement.supports("module"); > return "noModule" in document.createElement("script"); > 

Classic scripts are assumed to be supported on all browsers.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to Create a Script Element in JavaScript

Here’s how we can use JavaScript to create a script element in the HTML:

const script = document.createElement('script'); // use local file // script.src = 'script.js'; script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js'; script.async = true; // make code in script to be treated as JavaScript module // script.type = 'module'; script.onload = () => < console.log('Script loaded successfuly'); const box = document.getElementById('box'); box.textContent = 'The script has loaded.'; >; script.onerror = () => < console.log('Error occurred while loading script'); >; document.body.appendChild(script); 

The document.createElement() method creates an HTML element specified by the tag name and returns the element. By passing a script tag, we create a script element.

const script = document.createElement('script');

We set the src property on the script element to specify the script file to be loaded. We specify a remote file with a URL, but we could also specify a local file with a relative or absolute file path.

// use local file // script.src = 'script.js'; script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js';

By setting the async property to true , the browser won’t have to load and evaluate the script before continuing to parse the HTML. Instead, the script file will be loaded in parallel to reduce delays and speed up the processing of the page.

The type attribute indicates what type of script the file is. If it is a JavaScript module, we’ll need to set the type attribute to module to show this.

For a complete list of all attributes supported by the script element, visit the MDN docs on the script element.

We listen for the onload event in order to perform an action when the script file has been loaded successfully.

We listen for the onerror event so that we can perform a different action in case there was an error with loading the script.

The appendChild() method adds a DOM element as the last child of a specified parent element. By calling appendChild() on document.body , we add the script file to the body.

document.body.appendChild(script);

The script file is included in the body of the document.

To add the script file to the head of the document instead, we can replace document.body with document.head .

document.head.appendChild(script);

The script file is included in the head of the document.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Источник

Оцените статью