3

I have a javascript file that I reference in HTML with standard <script src="foo.js?param"></script>. In the file I want to distinguish e.g. loading the file with foo.js from foo.js?auto and foo.js?noauto=true, but not if the file is renamed to bar.js and referenced with the same parameter. How can I accomplish this, preferably not using any framework?

1

2 Answers 2

5

Take a look a scriptaculous' approach:

var js = /scriptaculous\.js(\?.*)?$/;
$$('head script[src]').findAll(function(s) {
  return s.src.match(js);
}).each(function(s) {
  var path = s.src.replace(js, ''),
  includes = s.src.match(/\?.*load=([a-z,]*)/);
  (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
   function(include) { Scriptaculous.require(path+include+'.js') });
});

I think it runs through all script elements and finds the reference to itself, and then parses that URL.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to do it reliably, then you need to provide different JS for each URL. You could generate it with a server side script.

If you want to do it in pure JS, then you can getElementsByTagName('script') and assume that last script is the one that matched (it might not be, e.g. if script elements are being added using DOM after the page has loaded).

1 Comment

Good idea, but I guess I should warn users not to change the name of the included file or call some method in case of explicit execution on load of body.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.