Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place 'script' before the end of BODY tags with jQuery

This is the 'script' I want before the 'body' tag:

<script type="text/javascript">
  var vglnk = { api_url: '//api.viglink.com/api',
                key: '89dcd0a12ff35d227eaaaff82503030b' };

  (function(d, t) {
    var s = d.createElement(t); s.type = 'text/javascript'; s.async = true;
    s.src = ('https:' == document.location.protocol ? vglnk.api_url :
             '//cdn.viglink.com/api') + '/vglnk.js';
    var r = d.getElementsByTagName(t)[0]; r.parentNode.insertBefore(s, r);
  }(document, 'script'));
</script>

I want this code to be where I've put "HERE"

<html>
<head>
</head>

<body>
    Some HTML and stuff
    HERE
</body>

</html>

How would I go about this in jQuery? (I'm doing this from an extension. Mainly in Chrome, but also Firefox and Internet Explorer.)

like image 946
Kyle Sterling Collins Avatar asked Mar 25 '13 22:03

Kyle Sterling Collins


People also ask

Can I place script tag outside body?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.

Why do you put script tags at the end of the body not in head?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Does script tag go in head or body?

The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

Why is it important to put the script tag at the end and not in the start?

We put the script elements at the end of the body, after all of the page's contents. This means the entire page will display as soon as it's available, and then the scripts will download to make things work.


1 Answers

You need the content script to do the insert on every page you want.

The code of the content script is really simple and doesn't need jQuery.

var code = "your script code here";
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);

As it will only be called once you don't even need to define a function. You can debug the code using debugger on any web the content script is attaching (F12) you will see your code in the content script tab.

like image 55
frisco Avatar answered Oct 18 '22 20:10

frisco