CreateJS/PreloadJS中‘tag loading’是什么?相关运作机制咨询
preferXHR: false Setting Great question—this is a common point of confusion when working with PreloadJS, so let’s break it down step by step.
What is 'Tag Loading'?
In the context of PreloadJS, tag loading refers to using native HTML elements (tags) to load resources, rather than relying on XMLHttpRequest (XHR/AJAX).
For example:
- Loading images with an
<img>tag (setting itssrcattribute to the image URL) - Loading scripts with a
<script>tag - Loading stylesheets with a
<link>tag - Loading audio/video with
<audio>/<video>tags
This leverages the browser’s built-in loading behavior for these elements, rather than manually fetching resources via an XHR request.
How does preferXHR: false affect PreloadJS?
By default, PreloadJS prioritizes using XHR to load resources (when preferXHR is true). When you set preferXHR: false, you’re telling the library to force the use of tag loading whenever possible, instead of falling back to XHR.
Key differences between XHR and Tag Loading (and why this setting matters)
Let’s compare the two approaches to understand the impact:
XHR Pros: Gives you fine-grained control over requests (custom headers, detailed progress tracking), allows you to load resources without automatically executing/rendering them (e.g., scripts won’t run immediately, images won’t be added to the DOM), and supports cross-origin requests if the server enables CORS.
XHR Cons: Requires CORS configuration for cross-origin resources, some resource types (like certain media) are harder to handle reliably, and browsers may have stricter limits on concurrent XHR requests.
Tag Loading Pros: Works seamlessly with cross-origin resources (no CORS required for most assets like images/scripts), resources are handled natively by the browser (e.g., scripts execute automatically once loaded, images are ready to use immediately), and it’s more compatible with older browsers or edge cases where XHR might fail.
Tag Loading Cons: Limited progress tracking (you can’t get detailed load percentages like with XHR), less control over request behavior, and loaded resources may auto-execute/render before you’re ready.
When would you use preferXHR: false?
Common scenarios include:
- You’re loading cross-origin resources that don’t have CORS enabled (XHR would throw an error here, but tag loading works)
- You want scripts to execute automatically as soon as they’re loaded
- You’re working with media assets (audio/video) that load more reliably via native tags
- You need broader compatibility with older browsers that have limited XHR support
内容的提问来源于stack exchange,提问作者monsto

