0

Having a bunch of 3rd party tracking and adservers scripts that are executed by using documnet.write() and I do believe using this method is not the best practice and instead one should use the dom friendly manipulation mentioned by anakata here

Now my question is where in the page(head, foot, body etc) and when (on page load, after the page is loaded or while the page is loading) can we fire these scripts?

current script example:

<script type="text/javascript">
var p = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + p + "clickops.net/clickops-tracker.v1.js' type='text/javascript'%3E%3C/script%3E"));
</script>

Can we use this snippet to append external scripts as a good example?

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "path/to/your/javascript.js";    // use this for linked script
document.head.appendChild(script);

I appreciate your valuable feedback.

Community
  • 1
  • 1
digitup
  • 529
  • 1
  • 6
  • 18

1 Answers1

1

Yes, you can use that (though I'd use document.head instead of #someElement).

Yet, if you have jQuery around you can use its already existing and very powerful ajax method:

$.ajax(url, {dataType: "script", cache:"true"});

or, if you don't want caching, also jQuery.getScript.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • Thank you so much. Shall I be concerned about the cross domain or any security issues using this method? – digitup Oct 22 '12 at 09:01
  • 1
    Um, loading 3rd party external scripts is *always* a security issue – Bergi Oct 22 '12 at 09:02
  • :I appreciate your feedback and time. That's why I am concerned regarding the security and I wanted to find a way which has a minimum security risk to be able to use it as a guideline for the vendors who need to place scripts on our site. I want to mention that our site is heavy eCommerce transactional site. – digitup Oct 22 '12 at 09:15
  • If you allow untrusted third parties executing scripts in *your* DOM, it is a security risk. – Bergi Oct 22 '12 at 10:44
  • Thank you, this is the important fact. How can we determine they are trusted or not? – digitup Oct 22 '12 at 11:34
  • That's part of your commerce. Do you trust Google to load only tracking scripts? Do you trust the ad networks? – Bergi Oct 22 '12 at 12:43
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18411/discussion-between-digitup-and-bergi) – digitup Oct 22 '12 at 14:04