Tip: Click lines to highlight, hold ctrl/cmd to multi-select

Detect insertion position (8-Apr @ 16:10)

By including this code in your external script, it will take note of position of the <script src="myscript.js"> element and allow you to run your content in once the DOM is ready.

remy

Syntax Highlighted Code

  1. (function () {
  2.     function getLastChild(el) {
  3.         return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;
  4.     }
  5.  
  6.     // should be our script tag
  7.     var insertPosition = getLastChild(document.lastChild);
  8.    
  9.     $(document).ready(function () {
  10.         // get widget via jsonp
  11.        
  12.         // target element should be create at insertPosition, i.e.
  13.         $(insertPosition).after('<p>widget inserted here</p>');
  14.     });
  15. })();

Plain Code

(function () {
    function getLastChild(el) {
        return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;
    }

    // should be our script tag
    var insertPosition = getLastChild(document.lastChild);
    
    $(document).ready(function () {
        // get widget via jsonp
        
        // target element should be create at insertPosition, i.e.
        $(insertPosition).after('<p>widget inserted here</p>');
    });
})();

Codedump Run

Permalink: http://codedumper.com/detect-insertion-position