Kris
Kris

Reputation: 4823

Why use Base64 encoding for JavaScript?

I've got a HTML file with embedded JavaScript like this:

<script src="data:application/x-javascript;base64,LyohIGpRdWVyeSB2MS4xMS4z ... ></script>

I found out that it is like normal JavaScript but in Base64 coding.

I used https://www.base64decode.org/ to decode the JavaScript and found that it's just the jQuery library.

Now I wonder what the reason might be to encode jQuery in Base64 instead of just load it with a <script type="application/javascript">? Especially if it's even larger than the original text (Why the size of base64-encoded string is larger than the original file)!

Edit: Have a look at the script in: https://gist.github.com/kristian-lange/7605e6cd2c643313022eb796e15458fa.

Upvotes: 3

Views: 3202

Answers (2)

Oriol
Oriol

Reputation: 288650

Probably because people don't know how to use the proper encoding, and then prefer to use base64, which usually works even if the encoding is wrong.

For example, this should work:

<script src="data:text/javascript,console.log('âàáäã')"></script>

However, if you use that in a UTF-8 file but don't tell the encoding to the browser, it might think it's something like windows-1252, and parse it as

<script src="data:text/javascript,console.log('âà áäã')"></script>

If you use base64, it will be

<script src="data:text/javascript;base64,Y29uc29sZS5sb2coJ8Oiw6DDocOkw6MnKQ=="></script>

And the browser will probably interpret it correctly, even if it attemps to read it using the wrong encoding.

Upvotes: 1

guest271314
guest271314

Reputation: 1

Portability. It is not necessary to make external request that may or may not succeed.

Upvotes: 0

Related Questions