开发者

appendChild before the node is completed loaded?

Can I appendChild a <script> element in the HEAD before the HEAD itself is completly loaded?

Example:

<head>
<script src="my.js">开发者_运维技巧;
//etc

in the my.js there is:

var thescript = document.createElement('script');
thescript.setAttribute('type','text/javascript');
thescript.setAttribute('src','otherfile.js');
document.getElementsByTagName('head')[0].appendChild(thescript);

this code will be executed before browsers reach </head>

is this safe or could cause problmes? I want to do this because I want load jquery from my .js script so i don't have to edit my pages to add the other <script> manually

Many Thanks


It's generally not safe to do DOM modification at this point in the page load, but a document.writeln('<script language="javascript" src="otherfile.js" />'); should be fine.


That's pretty much what the Google Analytics Asynchronous tracking code does and it doesn't usually encounter problems. Using a similar technique to GA it could look as follows:

(function() {
   var thescript = document.createElement('script');
   thescript.type = 'text/javascript';
   thescript.src = 'otherfile.js';
   var s = document.getElementsByTagName('script')[0]; 
   s.parentNode.insertBefore(thescript, s);
})();

However, remember that the code inside 'otherfile.js' might not be available straight away so you need to take that into consideration. GA uses a queue that you can add function calls to that will execute once the script is available.


The head element will not be available before it is fully loaded. You can use a different approach, though:

Include only one file, called "includes.js". It should look like this:

function include_once(src) {
  // get script elements already in the HTML source code,
  // abort if script has been loaded
  var scripts = document.getElementsByTagName('script');
  if ( scripts ) {
    for ( var k=0; k < scripts.length; k++) {
      if ( scripts[k].src == src ) return; 
    }
  }
  // include if not already loaded
  var script = document.createElement('script');
  script.src = src;
  script.type = 'text/javascript';
  (document.getElementsByTagName('head')[0] || document.body).appendChild(script);
}

// add all your scripts here
function addIncludes () {
    include_once ( 'js/my.js' );
}

Then, call addIncludes onload:

<body onload="addIncludes()">

(This example was taken and modified from a german site.)

If you have JS that has to be executed directly after loading, you need to set an interval and test for availability of the additional .js files - remember they are loaded after the original page is complete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜