Reputation: 12268
When I have test.js file and import the script with:
<script defer="defer" src="/js/test.js"></script>
everything works fine... but if I change the line above in html to:
<script defer="defer">
$(document).ready(function () {
$(".overviewPilotPortraitImage").click(function () {
alert("Hello world!");
});
});
</script>
it doesn't work anymore. test.js contains exactly the same script as above, just without script tags.
Yes, I'm sure it's exactly the same.
Head tag with test.js file - WORKING:
<head>
<title>Placeholder - Overview</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<script defer="defer" src="/js/jquery-1.11.1.min.js"></script>
<script defer="defer" src="/js/bootstrap.min.js"></script>
<script defer="defer" src="/js/test.js"></script>
</head>
Head tag with script in html - NOT WORKING:
<head>
<title>Placeholder - Overview</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<script defer="defer" src="/js/jquery-1.11.1.min.js"></script>
<script defer="defer" src="/js/bootstrap.min.js"></script>
<script defer="defer">
$(document).ready(function () {
$(".overviewPilotPortraitImage").click(function () {
alert("Hello world!");
});
});
</script>
</head>
First, I thought that the script is somehow loaded before the Jquery but it doesn't make sense since the file import works fine. Any ideas?
Upvotes: 2
Views: 918
Reputation:
Straight from w3schools (and MDN):
Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
So, basically, you cannot use your defer
attribute without the external script.
Perhaps try adding a window.onload
:
<script>
window.onload = function(){
$(document).ready(function () {
$(".overviewPilotPortraitImage").click(function () {
alert("Hello world!");
});
});
}
</script>
And putting your script tag within the body rather than the head.
<body>
<!--
bla - bla - bla
-->
<script>
// tags can go here
</script>
</body>
Upvotes: 2
Reputation: 4189
That's because defer has effect only on external scripts. You can declare the attribuite defer for in-page scripts but it is not considered by the browser.
In your second example, your in-page code is executed immediately, while jquery is loaded after the page has finished loading. More here.
Upvotes: 6