1

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?

3 Answers 3

4

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.

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

Comments

1

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.

Comments

-1

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

1 Comment

Defer=true gives a bad value error. And I already have the HTML doctype for html5

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.