How is the script type "text/html" utilized in contemporary applications? Is this specific example regarded as effective usage?

Is it considered good practice in today's standards to utilize something like the following code snippet and use jQuery to swap out content based on a selector?

<script type="text/html" id="this-content1">
<h1>This Header Info One</h1>
<p>This content one. . .</p>
</script>
<script type="text/html" id="this-content2">
<h1>This Header Info Two</h1>
<p>This content two. . .</p>
</script>

I am just starting to explore the use of script type="text/html"... to enable dynamic content changes and am discovering various approaches to achieve this. Is there a reliable source that explains the direction in which this practice is evolving and whether there is any standardization in place?

I often encounter code like the following...

<div class="thumbnail">
            <# if ( data.uploading ) { #>
                <div class="media-progress-bar"><div></div></div>
            <# } else if ( 'image' === data.type ) { #>
                <img src="{{ data.size.url }}" draggable="false" />
            <# } else { #>
                <img src="{{ data.icon }}" class="icon" draggable="false" />
            <# } #>
        </div>

...embedded within a script type="text/html" tag, and I am unsure of the rationale behind this structure. As someone who is just beginning to explore backbone, it seems a bit heavy-handed if the goal is simply to implement content swapping within a single page.

Answer №1

Based on the HTML5 guidelines for the script tag, it is considered acceptable to utilize the <script> element with a type attribute assigned to any valid MIME type, including options like text/html or text/plain.

However, the HTML4 specifications for the script tag offer a slightly different perspective:

"There are two types of scripts authors may attach to an HTML document: Those that are executed one time when the document is loaded [and t]hose that are executed every time a specific event occurs."

It is important to note that using templates does not necessarily require the implementation of Backbone. Alternatives such as jQuery or a personal preference like Mustache.js can also be effective for this purpose.

Answer №2

If you're looking to store a snippet of HTML for later use, it's important to avoid placing non-script data within a script tag. Facebook has a better approach!

<code class="hide" id="code1"><!--
  <p>My HTML content here</p>
  <script>My Javascript code here</script>
--></code>

By following Facebook's example, you can retrieve the HTML later and manipulate it as needed:

var html = document.querySelector('#code1').innerText.slice(5, -5)

The scripts embedded within the HTML won't be executed until you handle them appropriately.

Here are a few important points to consider:

  • It's unclear how innerText differs from other text retrieval methods
  • Inserting script tags directly into the DOM might not be straightforward. How jQuery accomplishes this remains a mystery

Answer №3

This code snippet demonstrates the process of embedding data directly into HTML using server-side rendering

As per information from Mozilla, it is possible to utilize the type attribute to embed data in HTML through server-side rendering by specifying a valid MIME type that is not JavaScript. For more details, check out https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

For instance:

<!-- Generated by the server -->
<script id="data" type="application/json">{"userId":1234,"userName":"John Doe","memberSince":"2000-01-01T00:00:00.000Z"}</script>

<!-- Static -->
<script>
  const userInfo = JSON.parse(document.getElementById("data").text);
  console.log("User information: %o", userInfo);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble reading the file using jQuery in Internet Explorer 8 and earlier versions due to its non-XML format (albeit resembling XML)

Currently, I am utilizing AJAX to load a KML file (which essentially functions as an XML file). The parsing works seamlessly in IE9, FF, and other browsers, but encounters issues in IE8. Although the data is retrieved, I face difficulties parsing it in jQu ...

After the page has finished loading, I aim to have the modal window pop up after 10 seconds. Thank you to all!

$(document).ready(function() { var id = "#dialog"; //Calculate screen dimensions var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Adjust mask to cover entire screen $('#mask').css({'wid ...

Challenges with splitting asynchronous code in NPM modules

Earlier, I posted a query on Stack Overflow I have recently established a local package within the main app's package.json: "contact-page": "file:local_modules/contact-page" The package.jsonmain and scripts sections for the contact module are confi ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

Passport - Pairing Plan "Error|The username provided for sign_request() is not recognized"

Currently experimenting with duo in node.js using passport to test its implementation in an application....Utilizing a passport-duo strategy and encountering issues when trying to apply the example provided in my own project. The GitHub repository for pass ...

Resolving the active tab problem within Angular 2 tab components

Can anyone assist in resolving the active tab problem within an angular 2 application? Check out the Plunker link I am using JSON data to load tabs and their respective information. The JSON format is quite complex, but I have simplified it here for cla ...

Trigger a drop-down list in React when typing a specific character, like {{ or @, in an input field

Is there a way in React.js to display a list or dropdown when a user types a certain character like '@' or '{{ }}' in the input text area? The user should be able to select an option from this list and have it inserted into the text are ...

New messages are revealed as the chat box scrolls down

Whenever a user opens the chatbox or types a message, I want the scroll bar to automatically move down to show the most recent messages. I came across a solution that seems like it will do the trick: The issue is that despite implementing the provided cod ...

How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time. Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be v ...

What could be causing the issue of being unable to connect to the NodeJS express server from any network?

Imagine having a web server running on port 3001 with the IP address 23.512.531.56 (obviously not a real one) and then switching to another network, like your neighbor's. Now, when you try entering 23.512.531.56:3001 in Chrome, why doesn't the se ...

javascript cannot utilize html reset functionality

My drop down menu includes an onChange event that triggers a JavaScript method. However, when I select a new value and then click the reset button, the dropdown reverts back to its original value but the onChange event does not fire. <select onChange= ...

The input field does not contain the chosen date

Utilizing the react-dates library from Airbnb for date selection has been a bit challenging in conjunction with redux form. Upon clicking the select date button, the calendar interface appears. However, upon choosing a date, the input box remains empty ins ...

ways to clear the float on the right side of an image

So I have two images that I am trying to float, like this: img{ float:left; clear:right; } <img src='http://img1.imgtn.bdimg.com/it/u=1005212286,2432746147&fm=21&gp=0.jpg' alt=''><br> <img src ...

Images on web pages are automatically resized to fit into a smaller preview window

Currently, I am facing an issue with the display of images in my grid windows on my website . The images are appearing as partial representations instead of rescaled versions where the whole picture is resized to fit the grid window. I have attempted mod ...

I am attempting to pass information through the body of an Axios GET request to be used in a Django backend, but when I try to print the request.body

As reported by Axios, it seems that this is a feasible solution: https://github.com/axios/axios/issues/462#issuecomment-252075124 I have the code snippet below where pos_title contains a value. export function getQuery(pos_code, id) { if (id === 94) ...

Is there anyone who can provide a comprehensive explanation for what is going on here?

{ // Let's figure out how to launch my HTML file as a webpage in Chrome. "version": "0.2.0", "configurations": [ { "type": "pwa-chrome", &q ...

Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something like this: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dumm ...

Challenges with text in a Bootstrap 5 responsive carousel

I'm currently in the process of developing a new website and I am utilizing bootstrap 5. One issue I have encountered is that the text and button within the carousel in the header section do not appear to be compatible. To provide better clarity, I wi ...

The deletion function necessitates a switch from a server component to a client component

I built an app using Next.js v13.4. Within the app, there is a server component where I fetch all users from the database and display them in individual cards. My goal is to add a delete button to each card, but whenever I try to attach an event listener t ...

`Considering various factors to alter class pairings`

I have defined a few style classes in my stylesheet as shown below: .left-align{ /* some styles here */ } .right-align{ /* some styles here */ } .validate-error{ /* some styles here */ } Depending on the type of data, I need to align the content ei ...