简体   繁体   中英

My javascript function works only after I hard refresh the page

I know that there are multiple questions about this same problem, but I couldn't find an answer in any of them. I'm using javascript to activate hover on other elements. The javascript code works fine but it only works after I hard refresh the page, CTRL + R. If I go to the page normally it won't work.

JS:

  $(function() { $('#faqBg').hover(function() { $('#spanContainer').css('background', 'rgb(0, 0, 0, 0.6'); }, function() { // on mouseout, reset the background colour $('#spanContainer').css('background', ''); }); }); 
 .image-wrapper { position: relative; } #faqBg { background: linear-gradient(-45deg,rgba(0,0,0,.5),rgba(0,0,0,.5)),url(https://images.pexels.com/photos/1239162/pexels-photo-1239162.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500); padding: 60px 0px; display: block; background-size: cover; background-repeat: no-repeat; } #spanContainer { color: #fff; width: 100%; text-align: center; padding: 20px 0px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="image-wrapper"> <div id="faqBg"> <div id="spanContainer"> Hover trigger </div> </div> </div> 

This is the code Im using, here when I do it everything seems allright, but on the website it doesnt. I tried adding $(document).ready and $(document).load but it didnt worked.

This is happening because of cache.

Add version to you javascript file on loading:

<script src="file.js?v=1"></script> Increment the v parameter on each change you want to see. If your page is generated dynamically you can set to v a timestamp value, depends on the backend language you are using.

Another solution is to use these meta tags:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

Use CSS instead:

 #faqBg:hover #spanContainer { 
       background: rgba(0,0,0,0.6);
 }

The javascript function in your code includes style change, which will be reflected after a hard refresh.

Can you please confirm whether any other JS function(a function without style change) acts the same way you mentioned.

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