简体   繁体   中英

Add defer to Scripts functions.php

In my site's functions.php script is like

add( 'scripts', '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' );

which shows on source code like

<script src="...jquery.min.js"></script>

want to add 'defer' to code like

<script src="...jquery.min.js" defer></script>

Please anyone guide me to achieve this?

By the file functions.php I assume that you are using WordPress. To defer loading javascript It's better to use a plugin like wprocket or other free variations of optimizer plugins.

But if you want to do it your self you can use below code:

function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) 
    return $url;
if ( strpos( $url, 'jquery.js' ) ) 
    return $url;

return "$url' defer ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );

Also if you are not on WordPress CMS you can use a script tag to achieve what you want. In the following code replace defer1.js, defer3.js, and defer3.js, etc. with the link of scripts that you want to defer.

function parseJSAtOnload() {
    var links = ["defer1.js", "defer2.js", "defer3.js"],
        headElement = document.getElementsByTagName("head")[0],
        linkElement, i;
    for (i = 0; i < links.length; i++) {
        linkElement = document.createElement("script");
        linkElement.src = links[i];
        headElement.appendChild(linkElement);
    }
}
if (window.addEventListener) {
    window.addEventListener("load", parseJSAtOnload, false);
}
else if (window.attachEvent) {
    window.attachEvent("onload", parseJSAtOnload);
}
else {
    window.onload = parseJSAtOnload;
}

You can use this

add( 'scripts', '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" defer="' );

So output:

<script src="...jquery.min.js" defer=""></script>

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