简体   繁体   中英

Loading Javascript and CSS files without DNS calls

If I reference javascript files in my header using full domain names is it slower to load than if I do it some other way?

$domain = 'https://www.example.com';
echo '<script src="'.$domain.'/js/index.js"></script>';

The problem is if I wasn't going to reference them directly I would need some way of handling it so they load even if the page is rewritten to a subfolder like https://www.example.com/subfolder/subfolder using .htaccess rewrite rules.

Is there a better, faster to load, yet still flexible way of doing this?

You seem to be confusing absolute URIs with a requirement for a DNS lookup.

Given an HTML document on http://example.com/index.html then the only difference between these two script elements:

<script src="/foo.js"></script>
<script src="http://example.com/foo.js"></script>

… is that the latter has an additional 18 bytes of HTML (which is insignificant even before you apply HTTP compression).

Whichever of the two approaches you use, the browser is going to resolve the URL to http://example.com/foo.js . If it has example.com in its DNS cache (which it will because it just loaded the HTML document), then it won't hit DNS servers to find out where to go for it.

What about this

$domain = $_SERVER['SERVER_NAME'];
echo '<script src="'.$domain.'/js/index.js"></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