I understand that I can trigger JavsScript on every page load when using turbolinks by using:
$(document).on('page:load', ready)
..but what's the best way to only trigger a JS block when a particular page (eg home page, so don't run JS for other pages) is loaded? I'm thinking to just wrap the content within a wrapper class like so for a page I have a specific piece of JS for:
<div class="homeWrapper">
...homepage...
</div>
..then do something like:
$(".homeWrapper .whatever") or $(".homeWrapper").find(".whatever")
.. but I'm worried if I have to do this for every pages elements on every page load it might slow the page down (too many jqueries). Is there a better way to do this, or is this the most common approach for Turbolink pages.
You could just use the .length()
function in JQuery to do this:
var el = $(".element");
if ( el.length > 0 ) {
//do something here
}
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.