document.head, document.body to attach scripts

后端 未结 4 874
死守一世寂寞
死守一世寂寞 2020-12-29 21:02

I have often used, and seen recommended, dom-access structures like this for adding content to pages dynamically:

loader = document.createElement(\'script\')         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 21:41

    I tried implementing this code and ran into a bit of trouble, so wanted to share my experience.

    First I tried this:

    
    

    And in the script.js file I had code such as the following:

    // This javascript tries to include a special css doc in the html header if windowsize is smaller than my normal conditions.  
    winWidth = document.etElementById() ? document.body.clientWidth : window.innerWidth; 
    if(winWidth <= 1280) { document.write(''); } 
    

    The problem is, when I did all of this, the code wouldn't work. Whereas it did work once I replaced the script loader with simply this:

    
    

    That works for me, so problem solved for now, but I would like to understand the difference between those two approaches. Why did one work and not the other?

    What's more is that in script.js I also have code such as:

    function OpenVideo(VideoSrcURL) {
    window.location.href="#OpenModal";
    document.getElementsByTagName('video')[0].src=VideoSrcURL;
    document.getElementsByTagName('video')[0].play();}
    

    And that code does work fine regardless of which way I source the script in my html file.

    So my window resizing script doesn't work, but the video stuff does. Therefore I'm wondering if the difference in behavior has to do with "document" object...? Maybe "document" is referencing the script.js file instead of the html file.

    I don't know. Thought I should share this issue in case it applies to anyone else.

    Cheers.

提交回复
热议问题