Use JavaScript to prevent a later `[removed]` tag from being evaluated?

前端 未结 7 719
北海茫月
北海茫月 2020-12-13 04:24

This is a bit of an oddball use case, but I have my reasons:

I\'d like to be able to write



        
7条回答
  •  Happy的楠姐
    2020-12-13 04:51

    Given your specific requirements set, this is actually quite simple and should work completely cross-browser. It does require however, that first.js immediately precedes second.js without anything between them except white space.

    First, let's assume that the HTML looks like this:

    
    
      
        Test Case
        
        
        
        
      
      
        

    Lorem ipsum dolor sit amet ...

    Run Func()

    I've removed the setTimeout because that can cause func() to run before start.js runs causing a "loadSecond is not defined" error. Instead, I've provided an anchor to be clicked on to run func().

    Second, let's assume that second.js looks like this:

    document.body.appendChild(document.createTextNode("second.js has run. "));
    if (window.meaningOfLife !== 42) {throw new Error();}
    

    Here, I've just added a line to append some text to the document body, so that it is easier to see when second.js actually runs.

    Then the solution for first.js is this:

    function loadSecond()
    {
        var runSecond = document.createElement("script");
        runSecond.setAttribute("src", "second.js"); 
        document.body.appendChild(runSecond);
    }
    
    document.write("
    
                                     
                  
提交回复
热议问题