DEV Community

Cover image for Can script tag have both src and content?
Abhii
Abhii

Posted on

Can script tag have both src and content?

You wanna be a software engineer at Google?
Sorry, this is not the part of our discussion today 😁

Can <script> tag have both src and content both?

Well the answer is Yes!! But the rendering is browser specific.

Many of the modern browsers don't run content at all when the script tag has src. If the injection is unsuccessful the browser will log the error as net::ERR_ABORTED 404 (Not Found) and if it is successful it will execute the src script.

According to html.spec.whatwg.org

For the Content model of script tag:

  • If there is no src attribute, depends on the value of the type attribute, but must match script content restrictions.
  • If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.

Many programmers tend to put the content inside script and then use DOM methods to get the content as string and then eval it. But this is not a good idea and hence must not be used.

So, What must be the content of the script which has src attribute?

HTML5 Draft specification suggests that <script> elements with src attribute must only include commented out code which gives the documentation of the script.

Again, there's a catch here as well. The following script will produce syntaxError:

<script src="main.js">
    var example = 'Consider this string: <!-- <script>';
    console.log(example);
</script>
Enter fullscreen mode Exit fullscreen mode

I know it's weird but it is JavaScript after all.

The reason for the error is that browser does not find the closing tag for the <script> tag as </script> is considered to be the closing tag for <script> on line:2

What is going on here is that for legacy reasons, "<!--" and <script> strings in script elements in HTML need to be balanced in order for the parser to consider closing the block.

To avoid such issues we can escape the <script> string as <\script> and thus our problems would be solved.

Wrapping up

  • Yes, <script> tag can have both src and content where content shall only include the commented out code that provides the documentation about the src used.
  • While using <script> as string always use escape sequence to avoid unnecessary problems. <script> string must be escaped as <\script> and </script> string as <\/script>

That's all for today! Hope you enjoyed the article and gained some
insights on the topic.
Or, Did I made you more confused? 😄

Thank You!!

Latest comments (2)

Collapse
 
zippytyro profile image
Shashwat Verma

I like that ad on top

Collapse
 
abhilearnstocode profile image
Abhii

It just clicks in my head at any random time everyday 😂