Johanna Ouwerling
Johanna Ouwerling

Reputation: 49

Error “Element script must not have attribute defer unless attribute src is also specified” from W3C validator

I have an HTML document whose source has a script element that has a defer attribute. The W3C validator says it isn't valid because it lacks the src attribute, but in fact there is a src attribute is in the source:

<script defer type="text/javascript">if($(window).width()>1024){document.write("<"+"script src='js/jquery.preloader.js'></"+"script>");}</script>

What can I do?

Upvotes: 1

Views: 3575

Answers (3)

sideshowbarker
sideshowbarker

Reputation: 88146

Maintainer of the W3C HTML Checker (validator) here.

The fix: put the script contents into a separate file and use the src attribute to reference that.

The checker reports an error for the snippet in the question because the HTML spec used to explicitly state that the script can’t have a defer attribute unless it also has a src attribute.

The spec no longer explicitly states that restriction, but I think that’s just an unintentional regression caused by a later spec change (which your question helped to catch—so, thanks!).

So I’ll investigate and raise a pull request for the spec fix and then update this answer later.

2018-05-05 update

For the record here, I did end up filing a pull request with an HTML spec patch:

https://github.com/whatwg/html/pull/2509

…and that was merged into the HTML spec source:

https://github.com/whatwg/html/commit/3c5180a08f90a375c64f8191f32f8c7ddfec0ba3

…and so now the current HTML spec once again states the restriction:

https://html.spec.whatwg.org/multipage/scripting.html#attr-script-defer

The async and defer attributes are boolean attributes that indicate how the script should be evaluated. Classic scripts may specify defer or async, but must not specify either unless the src attribute is present.

Upvotes: 4

Quentin
Quentin

Reputation: 943625

You have two <script> tags.

  • One which is in the HTML source
  • One which is generated using document.write.

The HTML one looks like this:

<script defer type="text/javascript">…</script>

It has no src attribute. That is why you get the error. You can't have a defer attribute there.

The one generated by JavaScript looks like this:

if ($(window).width()>1024){
    document.write("<"+"script src='js/jquery.preloader.js'></"+"script>");
}

It has a src attribute and doesn't have a defer attribute. You could add a defer attribute here.

It is also JavaScript so won't be treated as HTML by the validator anyway.

Upvotes: 1

1sloc
1sloc

Reputation: 1180

Try to set your DOCTYPE to HTML5. If not feasable, you'll probably need to write defer=true instead of defer.

Upvotes: -1

Related Questions