简体   繁体   中英

Why this Javascript code won't work on Chrome if Jquery loads as async?

I have a JavaScript in the WP theme I'm developing that hides part of the text inside <p> tag with the class "more". I set the Jquery to load as async in the header, but for some reason it works well on Firefox but not on Chrome. In my understanding, it's always good to use the async attribute with all independent scripts.

Header:

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/bootstrap.css">
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
<script async src="https://use.fontawesome.com/726be72ac8.js"></script>
<script  async src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The JavaScript code that provides the hide-text function goes right after the opening <body> . This way I assure it executes before the <p> tag is loaded:

<script>
$(document).ready(function() {
    var showChar = 150;
    var ellipsestext = "...";
    var moretext = "more";
    var lesstext = "less";
    $('.more').each(function() {
        var content = $(this).html();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(showChar-1, content.length - showChar);

            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

            $(this).html(html);
        }

    });

    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
});
</script>

Tag:

<p class="more">Text goes here</p>

If I remove the async attribute, it works fine on Chrome.

Adding async tells the browser that it's OK to run the jQuery script after your code - although that's not guaranteed and the script can run whenever the browser decides to run it. So it's just not appropriate in this case even if it works in Firefox.

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