I have designed custom navbar/menu. It currently calls CSS from my style.css and the JS which is used is included in the PHP file using the following setup
<link rel="stylesheet" href="style.css" type="text/css">
<nav> ... </nav>
<script>
$(function () {
$('.toggle-menu').click(function (){
$('.exo-menu').toggleClass('display');
});
});
jQuery(document).ready( function ( $ ){
$(".change>a").hover( function () {
$(this)[0].click();
},
function () {
/* code for mouseout */
});
});
</script>
The internal JS seems to be causing a problem with the CSS loading.
Is there any way I can load the called CSS before the JS whilst keeping it as is, without putting the Javascript on a seperate .js sheet?
So far have tried:
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body onload="initNavigation()">
<nav> ... </nav>
<script>
function initNavigation() {
$(function () {
$('.toggle-menu').click(function (){
$('.exo-menu').toggleClass('display');
});
});
jQuery(document).ready( function ( $ ){
$(".change>a").hover( function () {
$(this)[0].click();
},
function () {
/* code for mouseout */
});
});
}
</script>
</body/>
and
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<nav> ... </nav>
<script>
window.onload=function(){
$(function () {
$('.toggle-menu').click(function (){
$('.exo-menu').toggleClass('display');
});
});
jQuery(document).ready( function ( $ ){
$(".change>a").hover( function () {
$(this)[0].click();
},
function () {
/* code for mouseout */
});
});
}
</script>
</body/>
Can anyone tell me where I have went wrong? i am thinking its the .ready part but if it is, not sure how to get rid of it without affecting how the JS works?
Might it make a difference if I moved the JS to the head and placed it below the CSS?
-
1Why do you think the internal JS is causing a problem with the CSS loading? What kind of problem?user663031– user6630312017年09月26日 10:25:54 +00:00Commented Sep 26, 2017 at 10:25
-
Put the javascript just before the ending body tag.Rajendran Nadar– Rajendran Nadar2017年09月26日 10:30:06 +00:00Commented Sep 26, 2017 at 10:30
-
@Znaneswar your suggestion requires jQuery, but OP probably uses plain JS.Patrik Krehák– Patrik Krehák2017年09月26日 10:30:27 +00:00Commented Sep 26, 2017 at 10:30
1 Answer 1
Just use the onload event in your body tag and wrap your js in a function.
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body onload="initNavigation()">
<nav></nav>
<script>
function initNavigation() {
// your script goes here
}
</script>
</body>