4

I have a service where users embed a javascript code in they website, in the body tag. Sometimes the page where the code is embedded throws a javascript error from other javascript files which prevent our script from running.

Is there a way to design our code so it doesn't interfere with other javascript scope.

The only solution I can think of is to put the js code in an iframe.

5
  • 1
    Namespace it so it doesn't clash? Commented Sep 1, 2016 at 14:43
  • Yep sounds like you need to use a namespace: kenneth-truyers.net/2013/04/27/… Commented Sep 1, 2016 at 14:47
  • it is namespaced . But if there is a previous script that throws something like cannot call method x from null object all the javascript after that is ignored. Commented Sep 1, 2016 at 14:50
  • This is difficult to visualise now, can you post the code? And an example of an error which might happen? Commented Sep 2, 2016 at 6:11
  • Is my answer missing anything? Please be specific Commented Dec 8, 2016 at 4:49

1 Answer 1

2

The best way to make sure that your code always runs, is to make sure it is always loaded first.

As long as no scripts are dynamically loaded or marked as async or defer, scripts are run or evaluated in the order encountered in the page. So, the first scripts encountered run first.

In other words, by default, script tags are downloaded and evaluated sequentially as they are encountered in an HTML document.

An externally referenced script file that must be loaded will cause all further javascript execution to wait until that externally referenced file is loaded and parsed and runs.

What all of this means is that you should make sure your script is at the very top of the HTML that is being loaded, meaning it will be processed first and other scripts will not have a chance to interfere with yours.

reference: http://docstore.mik.ua/orelly/webprog/jscript/ch12_03.htm

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

Comments

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.