Dynamically Linked Libraries in WordPress: The Magic of Selective Asset Loading

WordPress is a powerful content management system that has revolutionized the way we build websites. However, like any framework, it has its limitations. One of the biggest challenges developers face when building websites with WordPress is the need to load all the code and assets for every plugin and component, regardless of whether they are needed on a particular page. This can cause slow loading times and impact site performance.

But what if we told you that there is a way to achieve dynamic asset loading in WordPress? By using a simple modification to the query, we can achieve selective asset loading and significantly improve site performance. Welcome to the world of dynamically linked libraries in WordPress!

Every page on a website has different size and complexity. Some pages require more assets than others, and some may not require any assets at all. By loading assets on a page-by-page basis, we can significantly improve site performance and reduce loading times. This is where dynamically linked libraries come into play.

Traditionally, WordPress loads all the code and assets for every plugin and component on every page, even if they are not needed. This can cause slow loading times and impact site performance. However, by using dynamically linked libraries, we can load only the assets that are required on a particular page, and leave out the rest. This can significantly improve site performance and reduce loading times.

So how do dynamically linked libraries work in WordPress? The process involves early post access, which allows us to retrieve the post ID before the wp hook. We can then scan the post content and metadata before enqueuing assets. This allows each page to be thoroughly customized with additional components and overrides, without impacting site performance.

<?php
/**
 *     URL to post ID
 *
 *     retrieves the post id of the main post or embeded post before the init hook
 *     with added support for Custom Types
 *
 *
 *     Requires main custom type settings to be set in a constant CT
 *     in settings/theme-ini
 *     ================================================================
 *
 */
function mrt_ct_url_to_postid( $url ) {
    # based on WP's url_to_postid()
    # copying the original function as is (almost)
    global $wp_rewrite;
    //$url = apply_filters( 'url_to_postid', $url ); // not sure what that does
    $url_host      = str_replace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );
    $home_url_host = str_replace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
    // Bail early if the URL does not belong to this site.
    if ( $url_host && $url_host !== $home_url_host ) {
        return 0;
    }
    // First, check to see if there is a 'p=N' or 'page_id=N' to match against
    if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) )   {
        $id = absint($values[2]); 
        if ( $id )
            return $id;
    }
    // Get rid of the #anchor
    $url_split = explode('#', $url);
    $url = $url_split[0];
    // Get rid of URL ?query=string
    $url_split = explode('?', $url);
    $url = $url_split[0];
    // Set the correct URL scheme.
    $scheme = parse_url( home_url(), PHP_URL_SCHEME );
    $url = set_url_scheme( $url, $scheme );
    // Add 'www.' if it is absent and should be there
    if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') )
        $url = str_replace('://', '://www.', $url);
    // Strip 'www.' if it is present and shouldn't be
    if ( false === strpos(home_url(), '://www.') )
        $url = str_replace('://www.', '://', $url);
    if ( trim( $url, '/' ) === home_url() && 'page' == get_option( 'show_on_front' ) ) {
        $page_on_front = get_option( 'page_on_front' );
        if ( $page_on_front && get_post( $page_on_front ) instanceof WP_Post ) {
            return (int) $page_on_front;
        }
    }
    // Check to see if we are using rewrite rules
    $rewrite = $wp_rewrite->wp_rewrite_rules();
    // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
    if ( empty($rewrite) )
        return 0;
    // Strip 'index.php/' if we're not using path info permalinks
    if ( !$wp_rewrite->using_index_permalinks() )
        $url = str_replace( $wp_rewrite->index . '/', '', $url );
    if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
        // Chop off http://domain.com/[path]
        $url = str_replace(home_url(), '', $url);
    } else {
        // Chop off /path/to/blog
        $home_path = parse_url( home_url( '/' ) );
        $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ;
        $url = preg_replace( sprintf( '#^%s#', preg_quote($home_path)), '', trailingslashit($url));
    }
    // Trim leading and lagging slashes
    $url = trim($url, '/');
    
    #
    # ### ### at this point we seem to have the nice little url to process, removing the rest of the original function
    #
    $url_parts= mrt_url_to_parts($url);
    if (!$url_parts) 
        return 0;
    
    $id= mrt_get_custom_type_id_from_url_parts($url_parts);
    if ($id) 
        return $id;
    return 0;
}
/** . . . . . . . . . . . . . . . . . . . . . . . . .
 *
 *
 *     retrieves the ID of the main page early
 *
 *     required by MRT
 *
 */
function mrt_MAIN_POST__ID(){
    ##
    #   special IDs
    #
    # Search results (also 0 results)
    if (strpos($_SERVER['REQUEST_URI'], '?s='))
        return -2;
    # Category
    $category_base= ''!=get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category';
    if (strpos($_SERVER['REQUEST_URI'], $category_base.'/' ))
        return -3;
    
    ##
    #   normal IDs
    # 
    # url_to_postid() seems to behave completely fine before the 'init' in most cases
    # also don't trust wp as it returns homepage's id for custom type
    if (0!=url_to_postid($_SERVER['REQUEST_URI']) && HOMEPAGE_ID!=url_to_postid($_SERVER['REQUEST_URI']))
        return url_to_postid($_SERVER['REQUEST_URI']);
    # check if by a chance it isn't a custom type and if so use our custom function instead
    if (0!=mrt_ct_url_to_postid($_SERVER['REQUEST_URI']))
        return mrt_ct_url_to_postid($_SERVER['REQUEST_URI']);
    #  url_to_postid() function doesn't seem to catch the homepage even if the latter is specified in wp admin settings
    #   - therefore a workaround involving the constant HOMEPAGE_ID that needs to be set early by hard-coding it in the [theme dir/settings/tmpl-fn.php] file
    #
    #  Homepage must be set in the WP's Admin screen > Reading > A static page > Homepage
    #
    if (!defined('HOMEPAGE_ID')){
        mrt_debug('?No homepage id specified');
        return 0;
    }
    # fallback to home
    return HOMEPAGE_ID;
}

There are very few things that are required on every single page, such as SEO optimization, cache management, redirections, and analytics. Other assets are usually optional. By separating global and optional assets, we can further improve site performance and reduce loading times.

In conclusion, dynamically linked libraries in WordPress are a game-changer for site performance and speed. By using selective asset loading, we can significantly improve site performance and reduce loading times, without sacrificing functionality or customization. If you’re a developer working with WordPress, it’s definitely worth exploring dynamically linked libraries and seeing how they can benefit your projects.