Reputation: 49
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
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
anddefer
attributes are boolean attributes that indicate how the script should be evaluated. Classic scripts may specifydefer
orasync
, but must not specify either unless thesrc
attribute is present.
Upvotes: 4
Reputation: 943625
You have two <script>
tags.
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
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