Front-end resource optimization method, system and device and computer storage medium
By recording dynamically loaded and statically parsed image resource identifiers in front-end projects, and combining reference validity and content redundancy analysis, unused and duplicate images are identified and optimized, solving the problem of resource waste in front-end projects and improving loading performance and user experience.
Patent Information
- Application Number
- CN202510800956.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-16
- Publication Date
- 2025-11-11
AI Technical Summary
In existing technologies, unused image files in front-end projects are difficult to accurately identify and clean up, leading to resource waste and performance bottlenecks, which affect user experience.
By recording the identifiers of dynamically loaded image resources during the runtime of the front-end project and combining them with statically parsed source files, a list of resource identifiers combining dynamic and static elements is generated. This list is then used to analyze the validity of references and the redundancy of content, and to identify and optimize incorrectly referenced, unused, and duplicate images.
It accurately identifies images with dynamic paths and images spliced using CSS variables in front-end projects, reducing project size and improving loading performance and user experience.
Smart Images

Figure CN120929146A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of data processing, and in particular to a method, system, apparatus, and computer storage medium for front-end resource optimization. Background Technology
[0002] In front-end projects, images are core visual elements that constitute the user interface. Their quantity and size directly affect application loading speed, user experience, and project maintenance costs. As projects iterate, image resources often only increase, leading to a gradual accumulation of unused image files, resulting in resource waste and potential performance bottlenecks. Therefore, accurately identifying and cleaning up unused images can effectively manage and optimize image resources in front-end projects, which greatly helps improve project quality.
[0003] In current technologies, most front-end projects often use image detection plugins to help retrieve unused image files, such as the webpack-unused-images-plugin. While these plugins offer convenience, their retrieval capabilities are limited. They primarily rely on static analysis of the module graph during the build process, meaning not all unused images can be accurately retrieved. For example, for images with dynamically concatenated paths, images referenced via variables in CSS preprocessors, and some complex dynamic loading scenarios, existing plugins may fail to effectively identify their usage status, resulting in some unused images being missed in the project. This hinders thorough optimization and negatively impacts user experience. Summary of the Invention
[0004] This application provides a method, system, apparatus, and computer storage medium for optimizing front-end resources to improve project loading performance and user experience.
[0005] The first aspect of this application provides a method for optimizing front-end resources, including: During front-end project runtime, record the first resource identifier corresponding to the dynamically loaded image; The source files of the front-end project are parsed to extract the second resource identifier corresponding to the statically referenced images in the front-end project; Integrate the first resource identifier and the second resource identifier to obtain a resource identifier list; Based on the image file set stored in the front-end project and the resource identifier list, a reference validity analysis is performed, and a content redundancy analysis is performed on the image file set; Based on the analysis results, target images are identified, and resource optimization operations are performed on the target images. The target images include incorrectly referenced images, unused images, and duplicate images.
[0006] Optionally, the reference validity analysis based on the image file set stored in the front-end project and the resource identifier list includes: Each resource identifier in the resource identifier list is matched against the set of image files stored in the front-end project to detect incorrectly referenced images; Each image file in the image file set is matched against the resource identifier list to detect unused images.
[0007] Optionally, the content redundancy analysis of the image file set includes: Each image file in the image file set is preprocessed, including scaling and grayscale processing. Calculate the perceptual hash value of the preprocessed image file, and detect duplicate images by comparing the perceptual hash values.
[0008] Optionally, the step of detecting duplicate images by comparing the perceptual hash values includes: Extract the first preset number of bits of the perceptual hash value as the feature code corresponding to the image file; One or more sets of image files with the same feature code in the image file set are identified as duplicate images.
[0009] Optionally, recording the first resource identifier corresponding to the dynamically loaded image during front-end project runtime includes: By overriding the constructor of the global image object, the first resource identifier of the image defined at the time of instantiation is monitored and recorded; Alternatively, the network data request interface can be packaged using a proxy pattern to intercept and record the first resource identifier of the image contained in the request for the image resource; Alternatively, by hijacking the node insertion operation of the document object model, the first resource identifier corresponding to the image dynamically added to the document can be monitored and recorded.
[0010] Optionally, parsing the source files of the front-end project and extracting the second resource identifier corresponding to the statically referenced images in the front-end project includes: Read and parse source files of preset types in the front-end project, including markup language files, script language files, and style sheet language files; By using regular expression matching or abstract syntax tree analysis, the second resource identifier of the image contained in the source file, such as image tag attributes, stylesheet URL function call parameters, or script module import instructions, is extracted.
[0011] Optionally, determining the target image based on the analysis results and performing resource optimization operations on the target image includes: The target image is determined based on the analysis results, and the user is prompted to select the corresponding resource optimization operation for the different types of target images. The resource optimization operation is performed on the target images of different types based on the user's selection.
[0012] A second aspect of this application provides a system for optimizing front-end resources, comprising: The recording unit is used to record the first resource identifier corresponding to dynamically loaded images during the runtime of the front-end project; The extraction unit is used to parse the source files of the front-end project and extract the second resource identifier corresponding to the statically referenced images in the front-end project; An integration unit is used to integrate the first resource identifier and the second resource identifier to obtain a resource identifier list; The analysis unit is used to perform reference validity analysis based on the image file set stored in the front-end project and the resource identifier list, and to perform content redundancy analysis on the image file set. The optimization unit is used to determine the target image based on the analysis results and perform resource optimization operations on the target image. The target image includes incorrectly referenced images, unused images, and duplicate images.
[0013] Optionally, the analysis unit is specifically used for: Each resource identifier in the resource identifier list is matched against the set of image files stored in the front-end project to detect incorrectly referenced images; Each image file in the image file set is matched against the resource identifier list to detect unused images.
[0014] Optionally, the analysis unit is further configured to: Each image file in the image file set is preprocessed, including scaling and grayscale processing. Calculate the perceptual hash value of the preprocessed image file, and detect duplicate images by comparing the perceptual hash values.
[0015] Optionally, the analysis unit is further configured to: Extract the first preset number of bits of the perceptual hash value as the feature code corresponding to the image file; One or more sets of image files with the same feature code in the image file set are identified as duplicate images.
[0016] Optionally, the recording unit is specifically used for: By overriding the constructor of the global image object, the first resource identifier of the image defined at the time of instantiation is monitored and recorded; Alternatively, the network data request interface can be packaged using a proxy pattern to intercept and record the first resource identifier of the image contained in the request for the image resource; Alternatively, by hijacking the node insertion operation of the document object model, the first resource identifier corresponding to the image dynamically added to the document can be monitored and recorded.
[0017] Optionally, the extraction unit is specifically used for: Read and parse source files of preset types in the front-end project, including markup language files, script language files, and style sheet language files; By using regular expression matching or abstract syntax tree analysis, the second resource identifier of the image contained in the source file, such as image tag attributes, stylesheet URL function call parameters, or script module import instructions, is extracted.
[0018] Optionally, the optimization unit is specifically used for: The target image is determined based on the analysis results, and the user is prompted to select the corresponding resource optimization operation for the different types of target images. The resource optimization operation is performed on the target images of different types based on the user's selection.
[0019] A third aspect of this application provides an apparatus for front-end resource optimization, the apparatus comprising: Processor, memory, input / output units, and bus; The processor is connected to the memory, the input / output unit, and the bus; The memory stores a program that the processor invokes to execute the first aspect and any optional front-end resource optimization method within the first aspect.
[0020] A fourth aspect of this application provides a computer-readable storage medium storing a program that, when executed on a computer, performs the first aspect and any optional front-end resource optimization method of the first aspect.
[0021] As can be seen from the above technical solutions, this application has the following advantages: By dynamically tracking and recording the actual images loaded during front-end project runtime, and combining this with the parsing of various source files in the project, a combined list of dynamic and static resource identifiers can be generated. Based on this resource identifier list, and by performing reference validity analysis and content redundancy analysis on the actual image file set stored in the front-end project, it is possible to accurately identify images with dynamic paths, images spliced from CSS preprocessor variables, images with the same content but different names, images imported in the code but actually missing, and images that exist in the project but are not referenced. Finally, resource optimization operations are performed on these identified target images, achieving more thorough front-end resource optimization, reducing project size, and improving project loading performance and user experience. Attached Figure Description
[0022] To more clearly illustrate the technical solutions in this application, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0023] Figure 1 A schematic flowchart of an embodiment of the front-end resource optimization method provided in this application; Figure 2 A schematic flowchart illustrating an embodiment of the front-end resource optimization method provided in this application, which includes citation validity analysis. Figure 3 A schematic flowchart illustrating an embodiment of content redundancy analysis in the front-end resource optimization method provided in this application; Figure 4 A schematic flowchart of an embodiment of the front-end resource optimization method provided in this application, which records the first resource identifier; Figure 5 A schematic flowchart illustrating an embodiment of the method for optimizing front-end resources provided in this application for extracting the second resource identifier; Figure 6 A schematic flowchart illustrating an embodiment of the front-end resource optimization method provided in this application; Figure 7 A schematic diagram of an embodiment of the system for optimizing front-end resources provided in this application; Figure 8 A schematic diagram of an embodiment of the front-end resource optimization apparatus provided in this application. Detailed Implementation
[0024] This application provides a method, system, apparatus, and computer storage medium for optimizing front-end resources to improve project loading performance and user experience.
[0025] It should be noted that the front-end resource optimization method provided in this application can be applied to terminals as well as servers. For example, a terminal can be a smartphone, computer, tablet, smart TV, smartwatch, mobile payment device, portable computer terminal, or a desktop computer, etc. For ease of explanation, this application uses a terminal as the execution subject for illustration.
[0026] Please see Figure 1 , Figure 1 An embodiment of the front-end resource optimization method provided in this application includes: S101. During the runtime of the front-end project, record the first resource identifier corresponding to the dynamically loaded image; In front-end projects, besides static declaration, a large number of images are dynamically created, requested, and added to the page by JavaScript during runtime based on user interaction, business logic judgments, or asynchronous API responses. The paths of these dynamically loaded images may not have direct, fixed link strings at the static code level, making them impossible to determine directly during the code writing phase, or their loading logic may be complex and difficult to record completely. Therefore, during the actual operation of the front-end project, it is necessary to monitor key JavaScript behaviors related to image loading and accurately record all dynamically loaded image resources. This recorded image information is the first resource identifier in this application. Specifically, when the front-end project runs, each time a dynamic image loading behavior is detected, the first resource identifier used to locate the image resource needs to be extracted from that dynamic image loading behavior.
[0027] The first resource identifier specifically refers to the unified identifier of the image resource captured through dynamic tracking. The identifier can be the URL address or relative path of the image, but the specifics are not limited here.
[0028] S102. Parse the source files of the front-end project and extract the second resource identifiers corresponding to the statically referenced images in the front-end project; Besides dynamically loaded images at runtime, images are more commonly referenced statically in the code in front-end projects. These image paths are usually hard-coded in the HTML. Static image references can be found through tags, the CSS `background-image` property, or via import statements and string assignments in JavaScript / TypeScript. Therefore, by parsing the source files of a front-end project, including HTML, CSS, JavaScript, TypeScript, Vue single-file components, and JSX / TSX components, these static image references can be identified. Further extraction of the URL or relative path of this reference is needed as a secondary resource identifier. This secondary resource identifier specifically refers to the Uniform Identifier (UUID) of the image resource captured through static parsing.
[0029] S103. Integrate the first resource identifier and the second resource identifier to obtain a resource identifier list; Because the first resource identifier for dynamically loaded images and the second resource identifier for statically referenced images are collected independently, inconsistencies in format and path may exist. For example, dynamically loaded images may be complete URLs, while statically referenced images may use relative paths, absolute paths, or path aliases. Furthermore, the same image resource may be dynamically loaded and statically referenced simultaneously, or statically referenced in multiple places, leading to duplicate identifiers in the first resource identifier. For subsequent analysis, it is necessary to integrate the first and second resource identifiers to obtain a unified and standardized list of resource identifiers.
[0030] Specifically, the first and second resource identifiers are first merged into an initial array. Then, path aliasing and replacement are performed on the resource identifiers in the initial array: the path aliases defined in the configuration files of the front-end project build tools (such as Webpack, Vite, etc.) are searched and parsed, and the mapping relationship between the aliases and their corresponding actual paths is extracted. Then, the initial array is traversed, and for each path string containing an identified alias, it is replaced with a relative or absolute path that does not contain an alias, based on the found mapping relationship. Afterwards, path normalization processing is required: all relative paths in the array are processed, and they are uniformly converted into path addresses relative to the project root directory, ensuring that all paths pointing to resources within the project have a unified expression starting from the project root directory. Finally, the array is deduplicated, ultimately generating an array of image addresses containing all dynamically loaded and statically referenced images with normalized paths and no duplicates, which is the resource identifier list in this application.
[0031] It should be noted that for dynamically loaded external image URLs, such as those from third-party APIs, since they cannot correspond to internal project files, their original URL format can be retained during integration. During alias resolution or path normalization, if an unresolved alias or invalid path format is encountered, the processing of that resource identifier will be skipped.
[0032] S104. Perform reference validity analysis based on the image file set and resource identifier list stored in the front-end project, and perform content redundancy analysis on the image file set; The resource identifier list represents all images that should theoretically be referenced in the front-end project. Simultaneously, the front-end project's directory structure also actually stores a set of image files, i.e., a unified folder containing the image file set. By combining the image file set and the resource identifier list, a comprehensive analysis of the front-end project's image resource status can be conducted, pinpointing issues such as broken links, wasted resources, and duplicate content. Specific analysis includes: Reference validity analysis aims to determine the consistency between statically referenced or dynamically loaded image resource identifiers (resource identifier list) and the actual image files existing in the project (image file set). Reference validity analysis primarily identifies two types of problems: incorrectly referenced images (the code references the image but the file does not exist) and unused images (the file exists but the code does not reference it).
[0033] Content redundancy analysis aims to check if multiple different image files in a set have identical or highly similar content. It's important to note that content redundancy analysis does not consider filenames or paths; it identifies duplicate resources directly based on the image content.
[0034] S105. Based on the analysis results, determine the target images and perform resource optimization operations on the target images. The target images include incorrectly referenced images, unused images, and duplicate images.
[0035] Based on the analysis results of reference validity analysis and content redundancy analysis, problematic target images in the front-end project can be identified. These target images specifically include incorrectly referenced images (referenced in the code, but the actual file does not exist), unused images (the actual file exists, but it is not referenced anywhere in the code), and duplicate images (multiple image files with identical or highly similar content, but possibly different filenames or paths). These target images are the targets for resource optimization. Different resource optimization operations can be performed based on the type of target image, including but not limited to: deleting the file, moving the file to a specific directory, generating a report to prompt users to fix the code, selectively retaining one copy of duplicate content, or automatically updating image references in the code.
[0036] Addressing incorrect image references can eliminate potential runtime errors. Removing unused and redundant duplicate images reduces the overall size of the front-end project, thereby speeding up builds, deployments, and client loading—all resource optimizations that improve user experience.
[0037] In this embodiment, by dynamically tracking and recording the actual images loaded during the front-end project's runtime, and combining this with the parsing of various source files in the project, a combined list of dynamic and static resource identifiers can be generated. Based on this resource identifier list, and by performing reference validity analysis and content redundancy analysis on the actual image file set stored in the front-end project, images with dynamic paths, images spliced using CSS preprocessor variables, images with the same content but different names, images imported in the code but actually missing, and images that exist in the project but are not referenced can be accurately identified. Finally, resource optimization operations are performed on these identified target images, achieving more thorough front-end resource optimization, reducing project size, and improving project loading performance and user experience.
[0038] The following provides a detailed explanation of the citation validity analysis in step S104. Please refer to [link / reference]. Figure 2 , Figure 2 As one embodiment of the citation validity analysis in this application, the method includes: S201. Match each resource identifier in the resource identifier list with the image file set stored in the front-end project to detect incorrect image references; During front-end development, code modifications, file renaming, moving, or accidental deletion may cause image paths referenced in the source code to not actually exist in the image file set specified in the front-end project. When the browser loads these references, it will display a broken image icon because the image resource cannot be found, affecting the visual integrity and professionalism of the page. Therefore, it is necessary to detect these erroneously referenced images to optimize front-end resources.
[0039] Due to front-end code standardization, all images used in the front-end project are placed in a single folder, which is the image file set in this application. File system operations (such as Node.js's `fs` and `path` modules) can be used to recursively read and concatenate the relative paths of all image files within the image file set path. For example, if the specified image file set directory is `src / images`, the system will scan all image files in all subfolders under that directory and generate a list of project image file paths similar to `['src / images / user / header.png', 'src / images / info / logo.png', ...]`. These paths are also normalized to a format relative to the project root directory for comparison with the paths in the resource identifier list.
[0040] Specifically, when detecting incorrectly referenced images, the process first iterates through each resource identifier in the resource identifier list. For each resource identifier, a regular expression is used to search the project's image file path list corresponding to the image file set for a path that exactly matches it. If a resource identifier in the resource identifier list cannot be matched in the project's image file path list corresponding to the image file set, it means that the code is referencing a non-existent image, and the image corresponding to this resource identifier will be marked as an incorrectly referenced image. Specifically, an incorrectly referenced image refers to an image resource identifier referenced in the front-end project's source code (including static declarations and dynamically generated ones), but for which the corresponding physical image file cannot be found in the image file set specified by the front-end project.
[0041] S202. Match each image file in the image file set with the resource identifier list to detect unused images.
[0042] As a project iterates, adjusts features, redesigns the UI, or refactors its code, some previously used images may be replaced by new ones, or related functions may be removed. This means that while these older image files may still be stored in the project's image archive, they are no longer referenced by any code. At this point, these images consume unnecessary disk space, increasing the size of the front-end project. Therefore, it's necessary to detect these unused images to optimize front-end resources.
[0043] Similar to step S201, the relative paths of all image files under the specified path in the image file set are recursively read and concatenated using file system operations to generate a standardized list of project image file paths relative to the project root directory. For each actual image file path in the project image file path list, a search is conducted in the resource identifier list to see if a path that exactly matches it exists. If no matching entry is found in the resource identifier list for an actual image file path in the project image file path list, it means that this actual image file is not referenced by any code in the project, and the image corresponding to this actual image file path will be marked as an unused image. Specifically, an unused image refers to an image file that physically exists in the image file set specified in the front-end project, but for which no valid reference can be found in the entire codebase of the front-end project (including dynamic loading logic and static declarations). These unused images are actually redundant resources in the front-end project.
[0044] In this embodiment, by performing a bidirectional matching search between the list of resource identifiers fully referenced in the code and the actual set of image files stored in the project, it can detect erroneous references to images in the code that are referenced but whose corresponding files are missing. This helps developers fix potential display errors and broken links in a timely manner, ensuring the stability of the application and the integrity of the user experience. At the same time, it can detect unused images that actually exist in the project but are not called by any code, providing developers with a direct and reliable basis for cleaning up redundancy, optimizing project size, improving build and loading efficiency, and reducing maintenance complexity.
[0045] The following provides a detailed explanation of the content redundancy analysis in step S104. Please refer to [link / reference]. Figure 3 , Figure 3 As one embodiment of the content redundancy analysis in this application, the method includes: S301. Perform preprocessing on each image file in the image file set. Preprocessing includes scaling and grayscale processing. In front-end projects, due to developers repeatedly introducing the same or visually similar materials in different modules or periods, uncleaned copies of old resources generated during version iterations, and a lack of unified resource management in multi-person collaborations, many substantially identical image files may appear in the image file set, but their filenames or paths may differ—these are duplicate images. In this embodiment, a perceptual hashing algorithm is specifically used to detect these duplicate images. The perceptual hashing algorithm mimics how the human eye processes images, generating unique fingerprints from image features for similarity comparison.
[0046] Different image files have different original dimensions and aspect ratios. Calculating perceptual hashes directly on images of different sizes will yield incomparable results. Therefore, image files need to be scaled to a fixed, preset size, such as 128x128 pixels. This allows subsequent perceptual hashing to analyze the image on the same dimension, ignoring differences in original size and focusing more on the image's macroscopic structure. Furthermore, color information is not a decisive factor in determining whether two images contain duplicate content; it may even be a distractor. For example, the core content of a color and black-and-white version of the same photograph, or a slightly color-corrected version, remains unchanged. Therefore, converting image files to grayscale removes color details, allowing a focus on fundamental visual features such as brightness distribution, contrast, edges, and texture, thus improving the robustness of subsequent perceptual hashing to color variations.
[0047] S302. Calculate the perceptual hash value of the preprocessed image file and detect duplicate images by comparing the perceptual hash values.
[0048] First, the preprocessed image files are converted to a specific format, such as a Buffer object in Node.js. Buffer objects can directly manipulate binary data, facilitating subsequent algorithmic processing. A perceptual hashing algorithm is then used to process the Buffer object. This algorithm performs a series of operations, such as further shrinking, calculating pixel averages / gradients, and performing discrete cosine transforms. The specific operations depend on the type of perceptual hashing algorithm used, ultimately generating a string in binary perceptual hash form, i.e., the perceptual hash value. This perceptual hash value is a high-level summary of the image's visual content; visually similar images will produce similar or identical perceptual hash values. Therefore, comparing perceptual hash values can detect duplicate images in a set of image files. A complete perceptual hash value is typically 64 bits. When comparing complete 64-bit hash values, Hamming distance is usually used to measure similarity; the smaller the Hamming distance, the more similar the images.
[0049] In some specific embodiments, to simplify the detection process, the first preset number of bits of the perceptual hash value can be extracted as the feature code corresponding to the image file; a group or more image files with the same feature code in the image file set are identified as duplicate images. For example, the first 16 bits of the perceptual hash value are extracted as the feature code of the image. If multiple image files are detected to have the exact same first 16 bits of the feature code, then these images are marked as duplicate images.
[0050] In this embodiment, by performing standardized preprocessing on each image file in the image file set, interference caused by differences in original image size, aspect ratio, and color is eliminated, ensuring that subsequent hash calculations can focus on the core structural features of the image. Subsequently, by calculating and comparing the perceptual hash values of these image files, image files that are highly consistent in core visual features can be quickly detected. This effectively identifies image resources in the project that have different paths or names but are essentially redundant in content, providing a basis for subsequent resource optimization operations.
[0051] There are multiple ways to dynamically load images during front-end project runtime. The following section details the process of recording the first resource identifier corresponding to the dynamically loaded image in step S101. Please refer to [link to relevant documentation]. Figure 4 , Figure 4 As one embodiment of recording a first resource identifier in this application, the method includes: S401. By overriding the constructor of the global image object, listen to and record the first resource identifier of the image defined at the time of instantiation; In front-end development, dynamically creating Image objects and setting their `src` attribute is a very common image preloading or on-demand loading technique. For example, in scenarios such as image carousels, lazy loading, or displaying different images based on user behavior, developers instantiate Image objects and dynamically specify their source. To implement this kind of dynamic loading monitoring, a custom function can be used to replace the browser's native Image constructor while ensuring that existing functionality remains unaffected; that is, the global image object's constructor is overridden. When this new Image constructor is called, it first creates a real image object instance to ensure the normal functionality of the image object. Then, it monitors the `src` attribute of this newly created image instance. When the image instance's `src` attribute is assigned a value, this value can be captured and recorded. This captured URL or path is considered the primary resource identifier.
[0052] S402. Wrap the network data request interface using the proxy pattern, intercept and record the first resource identifier of the image contained in the request for the image resource; However, in front-end projects, not all animated images are loaded using step S401. Many image resources, especially those with variable sources that need to be fetched from a server on demand, or those that are part of an API response, are obtained through general network request interfaces. For example, an image library application might request a list of image URLs via an API and then load them one by one; or an API endpoint might directly return binary streams of image files.
[0053] To listen for this type of dynamically loaded images, a proxy pattern can be used to wrap commonly used network data request interfaces in front-end projects, such as the fetch API or XMLHttpRequest objects, and libraries like Axios built upon them. The goal is to effectively intercept all network requests initiated by these interfaces without modifying the application's original business logic code. When the proxy captures an outbound network request, it examines the target URL and possible request or response characteristics to determine if the request is for retrieving image resources. Once confirmed as a request for image resources, the proxy extracts the complete URL of the image as the first resource identifier and records it. This approach can accurately track images dynamically loaded via asynchronous API calls, such as images retrieved from a server and displayed on demand, or images requested based on specific user actions.
[0054] S403. By hijacking the node insertion operation of the document object model, listen to and record the first resource identifier corresponding to the image dynamically added to the document.
[0055] Besides dynamically loading images via S401 and S402, developers often use standard DOM manipulation to dynamically insert image elements into web pages. To monitor this type of dynamic loading, the core prototype methods of the DOM (Document Object Model) responsible for node insertion can be intercepted to capture image resources dynamically created by JavaScript at runtime and directly added to the page's document structure. Specifically, custom logic can replace these native DOM manipulation methods. When the application calls these intercepted methods to insert a DOM node, this custom logic, after executing the original node addition function, checks whether the inserted node is an image element or another element whose image source is set via script. Once such dynamically added images are detected, the system extracts its valid source address (usually the src attribute value or the parsed CSS image URL) as the first resource identifier and records it. This method ensures that even if the image is not loaded through explicit image object instantiation or network requests, but rather dynamically rendered by directly manipulating the DOM structure, its first resource identifier can still be effectively tracked.
[0056] It should be noted that steps S401, S402, and S403 are not executed in a linear, sequential order, but rather are activated and work in parallel during project runtime, each responsible for listening to specific types of image loading events. Regardless of which monitored dynamic path the image is loaded through, the corresponding step will be triggered, recording the image's first resource identifier.
[0057] In this embodiment, a multi-dimensional and comprehensive dynamic image loading tracking system is constructed. The combination of steps S401, S402, and S403 can capture almost all possible scenarios of dynamic image loading in the front-end project to the greatest extent. This complementary monitoring strategy ensures that whether the image is created directly by JavaScript, loaded after asynchronously obtaining the image URL from the server API, or added by directly manipulating the DOM structure through scripts, its corresponding first resource identifier can be effectively recorded. This significantly improves the coverage and accuracy of dynamic image resource identification, makes up for the omissions that may exist in a single tracking method, and provides a foundation for subsequent resource optimization.
[0058] The following provides a detailed explanation of the process of extracting the second resource identifier corresponding to the statically referenced images in the front-end project in step S102. Please refer to [link / reference]. Figure 5 , Figure 5 As one embodiment of extracting a second resource identifier in this application, the method includes: S501. Read and parse source files of preset types in the front-end project. Preset types include markup language files, script language files, and style sheet language files. In front-end projects, static image referencing is a crucial component of image resource usage. These references are scattered across different types of files, such as the HTML structure, CSS styles, and JavaScript logic. To comprehensively understand which images are statically declared and used in a front-end project, it's essential to first read and parse source files of various types, including markup language files, script language files, and stylesheet language files. Markup language files define data structures and content presentation, such as HTML (.html) files, or component files containing HTML-like templates (e.g., the .vue portion of Vue, and the JSX portion of .jsx / .tsx files in React). Script language files contain program logic and dynamic behavior code, primarily JavaScript (.js) and TypeScript (.ts) and their variants (e.g., the script portions of .jsx and .tsx files). Stylesheet language files define the visual appearance of page elements (e.g., colors, layout, fonts), including standard CSS (.css) and CSS preprocessor language files (e.g., SCSS.scss, LESS.less).
[0059] S502. Extract the second resource identifier of the image from the source file by regular expression matching or abstract syntax tree analysis, such as image tag attributes, style sheet URL function call parameters, or script module import instructions.
[0060] Image references are embedded in different types of code using specific syntax: markup languages such as HTML / JSX use specific tags (e.g., ...). Image paths are typically defined using specific attributes (such as src, srcset) in CSS, SCSS, and LESS stylesheet languages, which usually specify the image path within the url() function. Scripting languages like JavaScript and TypeScript may reference images through module imports, string assignments, or specific API calls. Therefore, it is necessary to extract the specific image path or URL using regular expression matching or abstract syntax tree analysis.
[0061] Specifically, for cases with relatively simple syntax or very clear image referencing patterns, regular expressions can be used for direct matching, such as searching within an HTML string. Alternatively, you can search for `url(...)` in the CSS string to extract the secondary resource identifier. For script language files with more complex syntax, you can use Abstract Syntax Tree Analysis (AST) to convert the source code text into an AST tree structure, and then identify the specific type of node representing the image reference from these AST nodes, from which the corresponding secondary resource identifier can be extracted.
[0062] In this embodiment, by comprehensively scanning and reading all source files of preset types in the project, broad coverage of the analysis is ensured, and no potential image reference sources are missed. Subsequently, regular expression matching or abstract syntax tree analysis is used to extract image tag attributes, CSS url() call parameters, and second resource identifiers contained in script module import instructions from the complex content and specific syntactic structures of these different types of source files, maximizing the identification of all statically declared or hard-coded image references in the project.
[0063] In the preliminary steps of the front-end resource optimization process, potentially problematic image resources in the project have been identified through dynamic tracking, static parsing, reference validity analysis, and content redundancy analysis. However, directly performing automated operations on these identified images may be risky. Therefore, resource optimization can be combined with user decisions. The resource optimization operations in step S105 are explained in detail below. Please refer to [link / reference]. Figure 6 , Figure 6 As one embodiment of resource optimization in this application, the method includes: S601. Determine the target image based on the analysis results and prompt the user to select the corresponding resource optimization operation for different types of target images; First, based on the analysis results, the target images to be optimized are identified, including incorrectly referenced images, unused images, and duplicate images. Then, irreversible resource optimization operations are not immediately executed automatically. Instead, a series of corresponding resource optimization options are provided for different types of target images. For example, for unused images, options might be to delete, move to a backup folder, or ignore; for incorrectly referenced images, options might be to check the reference location and mark it as needing repair; for duplicate images, options might be to keep one copy and delete the others or keep all. This gives users the final decision-making power, allowing them to choose the most appropriate resource optimization method based on the specific project situation and their own judgment, while also greatly enhancing the security and controllability of the resource optimization process.
[0064] S602. Perform resource optimization operations on different types of target images based on the user's selection.
[0065] After the user makes their selections, the system can process these target images individually or in batches based on those selections. For example, if the user chooses to delete a batch of unused images, the system will perform file deletion, ideally moving them to the recycle bin or a recoverable backup directory. If the user chooses to keep a specific copy of a set of duplicate images and remove the rest, the system will delete those copies marked as redundant. If the user marks incorrectly referenced images, the system will record this information for developers to track and fix in subsequent code. Simultaneously, detailed operation logs can be recorded during resource optimization, and the results will be fed back to the user after the operation is completed.
[0066] In some specific implementations, since unused images pose the least risk of disrupting existing project functionality, they can be prioritized for automatic deletion, thereby directly and quickly reducing project size. After deleting these explicitly redundant resources, users are then prompted to manually handle incorrectly referenced and duplicate images. Since fixing incorrectly referenced images often involves understanding the code logic, user-led resource optimization decisions are more accurate. Handling duplicate images may require users to determine which copy should be the standard version, whether to integrate reference paths to different copies in the code, and whether such integration might introduce other problems. These decisions also heavily rely on the user's judgment of the specific project context.
[0067] The following provides a detailed description of the front-end resource optimization system provided in this application. Please refer to [link / reference]. Figure 7 , Figure 7 Another embodiment of the system for optimizing front-end resources provided in this application, the system includes: Recording unit 701 is used to record the first resource identifier corresponding to the dynamically loaded image during the runtime of the front-end project; Extraction unit 702 is used to parse the source files of the front-end project and extract the second resource identifier corresponding to the statically referenced images in the front-end project; Integration unit 703 is used to integrate the first resource identifier and the second resource identifier to obtain a resource identifier list; Analysis unit 704 is used to perform reference validity analysis based on the image file set and resource identifier list stored in the front-end project, and to perform content redundancy analysis on the image file set; The optimization unit 705 is used to determine the target image based on the analysis results and perform resource optimization operations on the target image. The target image includes incorrectly referenced images, unused images, and duplicate images.
[0068] Optionally, analysis unit 704 is specifically used for: Each resource identifier in the resource identifier list is matched against the set of image files stored in the front-end project to detect incorrect image references; Each image file in the image file set is matched against the resource identifier list to detect unused images.
[0069] Optionally, the analysis unit 704 is also specifically used for: Each image file in the image file set is preprocessed, including scaling and grayscale processing. Calculate the perceptual hash value of the preprocessed image file, and detect duplicate images by comparing the perceptual hash values.
[0070] Optionally, the analysis unit 704 is also specifically used for: Extract the first preset number of bits of the perceptual hash value as the feature code corresponding to the image file; A set of one or more image files with the same signature is identified as duplicate images.
[0071] Optionally, the recording unit 701 is specifically used for: By overriding the constructor of the global image object, the first resource identifier of the image defined at the time of instantiation is monitored and recorded; Alternatively, the network data request interface can be wrapped using a proxy pattern to intercept and record the first resource identifier of the image contained in the request for the image resource; Alternatively, by hijacking the node insertion operation of the document object model, the first resource identifier corresponding to the image dynamically added to the document can be monitored and recorded.
[0072] Optionally, the extraction unit 702 is specifically used for: Read and parse source files of preset types in the front-end project. The preset types include markup language files, script language files, and stylesheet language files. By using regular expression matching or abstract syntax tree analysis, the second resource identifier of the image is extracted from the source file, including image tag attributes, stylesheet URL function call parameters, or script module import instructions.
[0073] Optionally, the optimization unit 705 is specifically used for: The analysis results determine the target images, and the user is prompted to select the corresponding resource optimization operations for different types of target images. Perform resource optimization operations on different types of target images based on the user's selection.
[0074] In this embodiment, the functions of each unit are the same as described above. Figures 1 to 6 The steps in the method embodiments shown correspond to those in the examples, and will not be repeated here.
[0075] This application also provides a front-end resource optimization apparatus; please refer to [link / reference]. Figure 8 , Figure 8 One embodiment of the front-end resource optimization apparatus provided in this application includes: Processor 801, memory 802, input / output unit 803, bus 804; The processor 801 is connected to the memory 802, the input / output unit 803, and the bus 804; The memory 802 stores a program, and the processor 801 calls the program to execute any of the front-end resource optimization methods described above.
[0076] This application also relates to a computer-readable storage medium on which a program is stored, which, when run on a computer, causes the computer to perform any of the above-described front-end resource optimization methods.
[0077] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the specific working processes of the systems, devices, and units described above can be referred to the corresponding processes in the foregoing method embodiments, and will not be repeated here.
[0078] In the several embodiments provided in this application, it should be understood that the disclosed systems, apparatuses, and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be an indirect coupling or communication connection between apparatuses or units through some interfaces, and may be electrical, mechanical, or other forms.
[0079] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0080] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0081] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this application. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.
Claims
1. A method for optimizing front-end resources, characterized in that, The method includes: During front-end project runtime, record the first resource identifier corresponding to the dynamically loaded image; The source files of the front-end project are parsed to extract the second resource identifier corresponding to the statically referenced images in the front-end project; Integrate the first resource identifier and the second resource identifier to obtain a resource identifier list; Based on the image file set stored in the front-end project and the resource identifier list, a reference validity analysis is performed, and a content redundancy analysis is performed on the image file set; Based on the analysis results, target images are identified, and resource optimization operations are performed on the target images. The target images include incorrectly referenced images, unused images, and duplicate images.
2. The method according to claim 1, characterized in that, The reference validity analysis based on the image file set stored in the front-end project and the resource identifier list includes: Each resource identifier in the resource identifier list is matched against the set of image files stored in the front-end project to detect incorrectly referenced images; Each image file in the image file set is matched against the resource identifier list to detect unused images.
3. The method according to claim 1, characterized in that, The content redundancy analysis of the image file set includes: Each image file in the image file set is preprocessed, including scaling and grayscale processing. Calculate the perceptual hash value of the preprocessed image file, and detect duplicate images by comparing the perceptual hash values.
4. The method according to claim 3, characterized in that, The step of detecting duplicate images by comparing the perceptual hash values includes: Extract the first preset number of bits of the perceptual hash value as the feature code corresponding to the image file; One or more sets of image files with the same feature code in the image file set are identified as duplicate images.
5. The method according to claim 1, characterized in that, The process of recording the first resource identifier corresponding to dynamically loaded images during front-end project runtime includes: By overriding the constructor of the global image object, the first resource identifier of the image defined at the time of instantiation is monitored and recorded; Alternatively, the network data request interface can be packaged using a proxy pattern to intercept and record the first resource identifier of the image contained in the request for the image resource; Alternatively, by hijacking the node insertion operation of the document object model, the first resource identifier corresponding to the image dynamically added to the document can be monitored and recorded.
6. The method according to claim 1, characterized in that, The step of parsing the source files of the front-end project and extracting the second resource identifier corresponding to the statically referenced images in the front-end project includes: Read and parse source files of preset types in the front-end project, including markup language files, script language files, and style sheet language files; By using regular expression matching or abstract syntax tree analysis, the second resource identifier of the image contained in the source file, such as image tag attributes, stylesheet URL function call parameters, or script module import instructions, is extracted.
7. The method according to any one of claims 1 to 6, characterized in that, The step of determining the target image based on the analysis results and performing resource optimization operations on the target image includes: The target image is determined based on the analysis results, and the user is prompted to select the corresponding resource optimization operation for the different types of target images. The resource optimization operation is performed on the target images of different types based on the user's selection.
8. A system for optimizing front-end resources, characterized in that, The system includes: The recording unit is used to record the first resource identifier corresponding to dynamically loaded images during the runtime of the front-end project; The extraction unit is used to parse the source files of the front-end project and extract the second resource identifier corresponding to the statically referenced images in the front-end project; An integration unit is used to integrate the first resource identifier and the second resource identifier to obtain a resource identifier list; The analysis unit is used to perform reference validity analysis based on the image file set stored in the front-end project and the resource identifier list, and to perform content redundancy analysis on the image file set. The optimization unit is used to determine the target image based on the analysis results and perform resource optimization operations on the target image. The target image includes incorrectly referenced images, unused images, and duplicate images.
9. A device for optimizing front-end resources, characterized in that, The device includes: Processor, memory, input / output units, and bus; The processor is connected to the memory, the input / output unit, and the bus; The memory stores a program, which the processor invokes to perform the method as described in any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that, The computer-readable storage medium contains a program that, when executed on a computer, performs the method as described in any one of claims 1 to 7.