1

I hava some js code below,what's the data in src? how does it works?

script.src = "data:text/javascript,inc++"

details:

    <script>
        //Initialize the "inc" to zero.
        var inc = 0;
        //Get the HEAD element from the document.
        var head = document.documentElement.firstChild;
        //Create and initialize SCRIPT elements in a loop,
        //they will execute 2 times of the "inc++" code.
        for (var i = 0; i < 2; i++) {
            var script = document.createElement("script");
            script.src = "data:text/javascript,inc++"; // how does the data works?
            head.insertBefore(script, head.firstChild);
            script.onload = function () {
                console.log(inc);
            };
        };
    </script>

the src value should be setted a url,but this does not. why so?

6
  • It is a data URI Commented Mar 12, 2019 at 7:17
  • use script.src = "data:text/javascript," + inc++; Commented Mar 12, 2019 at 7:20
  • I believe you would need to encode it with base 64 Commented Mar 12, 2019 at 7:22
  • 1
    @לבני-מלכה that would be "data:text/javascript,0" Commented Mar 12, 2019 at 7:23
  • @jro I know it looks like the OP wats it (see he initializes the "inc" to zero.) Commented Mar 12, 2019 at 7:25

1 Answer 1

1

From the MDN docs for the script tag:

src

This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document.

⚠️ If a script element has a src attribute specified, it should not have a script embedded inside its tags.

How can you embed a script directly within a document (other than embedding it between <script> tags)?

Here's another excerpt from MDN docs, on data URI:

Data URLs, URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents.

data:text/javascript indicates that it's a javascript document. Other type of interest is data:text/html, you can also do something like data:text/html,<script>/* some js code */</script>

I have seen it being more commonly used to embed small image in css, i.e

div {
  background: url(data:image/png;base64,....); <-- image encoded in base64
}

So your example is basically equivalent to:

<script>
  var inc = 0;
  for (var i = 0; i < 2; i++) {
    var script = document.createElement("script");
    inc++;
    console.log(inc);
  };
</script>

Your excerpt of code perhaps is meant to explain how script tags behave.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.