How to go about checking the presence of a javascript file on a given web page from a web server

StackOverflow https://stackoverflow.com/questions/21907160

  •  14-10-2022
  •  | 
  •  

Question

I am working on an app that needs to inject a script in a client web page via a snippet (A lot like how google analytic does it) so that's part is pretty straight forward.

Problem is now that i'd like to be able to notify user if the script has not been detected on the client page. For that i was thinking to serve the client script via a backend script for instance

<script src="pathTo/script/?ID=someUniqueID"></script>

That way i can run some logic on the back-and and keep track of whether or not the script for that page has already been loaded.

The downside i see to that approach are :

  1. the script wont be cached when the uniqueID changes
  2. Some overhead to run a backend logic that is really only used once

Knowing that i can not use real time for this particular app, are there any alternatives? .

I have seen apps loading scripts with a get parameter like :

somescript.js?param=true

Anyone know what that is ?

EDIT: Other solution that just came to me: Curling the page from the server and then parsing the DOM to look for the script. I could for instance add an ID to the script tag to make that easier.

Thanks

Was it helpful?

Solution

The difference between your first and second approach is that for the first approach the user needs to load the page first and in your second approach (server retrieving the webpage), the user doesn't have to load the page (because the server does that).

If it's allowed to make the user first visit the page, then you can also use some additional approaches:

You can make your script notify the server by an AJAX request for example (so the client notifies the server that the script has loaded). The disadvantages of this method are:

  • Always sends an AJAX request (if it's only required once it might be a useless overhead)
  • Problems may occur with cross domain requests (they can be solved)

Another way is that you intercept all calls to the server (can be done with a reverse proxy) and keep logs of the Referrer header (contains the page that requested the script). But similar to your conclusion, this adds an additional overhead.

I think the conclusion is that it's hard to prevent an additional overhead (either on the server or the client), the only exception is of course the server retrieving the page (your second idea with curl). So in the end that might be the best solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top