ArticleZip > Check If Javascript Script Exists On Page

Check If Javascript Script Exists On Page

JavaScript is a fundamental part of modern web development. When working on a website or web application, you may need to check whether a specific JavaScript script is present on a page. This can be useful for various reasons, such as ensuring script dependencies are met before executing code, enhancing user experience, or debugging issues related to script loading.

Here's a simple and effective way to check if a JavaScript script exists on a page using vanilla JavaScript:

First, we need to understand that all JavaScript scripts are represented as `` elements in the HTML document. To check if a script exists, we can iterate through all the `` elements on the page and compare their `src` attribute to the script we are looking for.

Here's how you can implement this:

1. Get all the `` elements on the page:

Javascript

const scriptElements = document.querySelectorAll('script');

2. Loop through each `` element and check if the `src` attribute matches the script URL you are looking for. If a match is found, the script exists on the page.

Javascript

function isScriptLoaded(src) {
  for (let script of scriptElements) {
    if (script.src === src) {
      return true;
    }
  }
  return false;
}

// Usage example
if (isScriptLoaded('https://example.com/script.js')) {
  console.log('Script exists on the page!');
} else {
  console.log('Script does not exist on the page.');
}

In the example above, the `isScriptLoaded` function takes the script URL as an argument and checks each `` element's `src` attribute. If a match is found, it returns `true`, indicating that the script exists on the page. Otherwise, it returns `false`.

By utilizing this method, you can dynamically check for the presence of JavaScript scripts on your web pages. This can be especially helpful in scenarios where you need to conditionally load additional scripts or execute certain actions based on script availability.

Remember, managing script dependencies is crucial for maintaining a well-structured and efficient web application. By verifying the existence of JavaScript scripts on your pages, you can ensure smoother functionality and better overall user experience.

So, next time you need to check if a JavaScript script exists on a page, feel free to use this simple approach to enhance your coding practices and streamline your web development process. Happy coding!

×