简体   繁体   中英

Which is better for my simple but working javascript embed code (and why?)

This is probably an easy question for most of you and perhaps I'm styling this post too much but I just hope it helps in getting a good answer (to my first question).

Background

I want to create a simple banner/visual so multiple primary schools can display that they belong to a larger non-profit organization (eg. the "umbrella brand").

Since most schools have their own websites and webmasters, CMS-es etc. I want to give out a simple line of JS for the webmaster to implement in the template / html. Just like fi Google Analytics tag or service like Intercom.

Requirements

  1. Easy to implement (copy/paste)
  2. Asynchronous so it will not interfere with the pagespeed etc.
  3. No iFrame

My solution

I wrote a simple working javascript (createBanner.js) which creates a DIV with CSS/HTML and will be hosted on an external website:

var logo = document.createElement("div");
logo.innerHTML =
    '<span style="height: 100px;width: 100px; background: red; position: fixed; right: 10px;top: 10px;z-index: 99999;"></span>\n' 
document.body.appendChild(logo);

I will ask schools to implement an embed script and have 2 versions.

Embed script version 1:

<script>
var script = document.createElement('script');
script.src = "//externaldomain.com/createBanner.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>

Embed script version 2:

<script async src="//externaldomain.com/createBanner.js"></script>

My questions:

  1. Which of the two embed scripts is best for me to use? Or is there an even better way?

  2. Can these methods also be used for more elaborate javascript in the future?

Thank you for your help.

Best regards, Dennis

Depend on your usecase, but if your script has no dependencies in the DOM or other script, just go for the second one. If yes, go for the first.

But since the requirement itself stated that it should be async, the second one it is

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM