简体   繁体   中英

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?

Maintainer of the W3C HTML Checker (validator) here.

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

The checker reports an error for the markup 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 seems to explicitly state 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM