Does .load() retrieve Javascript?

So, I have a div with Javascript (and PHP) in it:

<div id="getItems">
<script>
    sessionStorage.setItem('numItems', <?php echo $_SESSION['NumItems'];?>);
</script>
</div>

I'd like to selectively reload this div, to get the most current value of numItems.

Something like:

$( "#getItems" ).load( window.location + " #getItems" );
var numItems = sessionStorage.getItem('numItems');

Will the .load() method retrieve and run the Javascript within the div?

Or does .load() only pass html into the div?

2 answers

  • answered 2020-01-14 01:25 CertainPerformance

    If the parameter passed to .load didn't contain a selector at the end, then yes, scripts inside will be run.

    But since you called .load with a selector, any scripts inside will not be run. See jQuery documentation:

    Script Execution

    When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

    Here, any JavaScript loaded into #a as a part of the document will successfully execute.

    $( "#a" ).load( "article.html" );
    

    However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

    $( "#b" ).load( "article.html #target" );
    

    Your case is the second, so inline <script>s will be stripped out and not run.

    If you want to update the value for NumItems on the client, don't use .load - instead, make a network request to a PHP script which only echos $_SESSION['NumItems'], and set the response to the sessionStorage item.

  • answered 2020-01-14 01:29 Aidan Chase

    The .load() method only loads the following data:

    url Type: String A string containing the URL to which the request is sent. data Type: PlainObject or String A plain object or string that is sent to the server with the request. complete Type: Function( String responseText, String textStatus, jqXHR jqXHR ) A callback function that is executed when the request completes.

    It appears to me that you can pass in a file-path as an argument to the method and any javascript logic within that file will execute.

    However;

    Here, any JavaScript loaded into #a as a part of the document will successfully execute.

    $( "#a" ).load( "article.html" );
    

    However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

    $( "#b" ).load( "article.html #target" );