Reputation: 57
I read it in many articles that, "it is a good practice to listen for global init event in order to trigger your application logic only after the event has been fired". But I tried to do otherwise still no problem occurs. When I check the network tab all, irrespective of the placement of the code, the core libraries are loaded first. Then the code dependent on libraries is loaded.
I tried searching for my answer but couldn't get a clear answer. I tried to check it using a sample code I wrote. But no success.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<title>My Pets</title>
<script id="test"
src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_belize"
data-sap-ui-libs="sap.m">
</script>
<script>
var oImage2 = new sap.m.Image({
src: "img/cat_sad.jpg",
decorative: false,
alt: "sad cat"
});
oImage2.placeAt("content");
alert("different_script_tag");
</script>
<script>
sap.ui.getCore().attachInit(function() {
alert("inside_attachinit");
var oImage1 = new sap.m.Image({
src: "img/dog_sad.jpg",
decorative: false,
alt: "sad dog"
});
oImage1.placeAt("content");
});
alert("outside_attachinit");
</script>
</head>
<body id="content" class="sapUiBody">
</body>
</html>
I wish to know, if browser already prioritizes the requests accordingly for us, why we are told to follow this good practice?
Upvotes: 1
Views: 439
Reputation: 18054
It is not only "a good practice", it's absolutely necessary in order to enable asynchronous loading.
Activating asynchronous loading of modules requires listening to the init
event. Otherwise, the app will crash because you're trying to access Image
from sap.m
although that library hasn't been loaded yet:
<script id="sap-ui-bootstrap" src="https://ui5.sap.com/resources/sap-ui-core.js" data-sap-ui-theme="sap_belize" data-sap-ui-libs="sap.ui.core, sap.m" data-sap-ui-async="true" ></script> <script> var oImage2 = new sap.m.Image(/*...*/); // Uncaught TypeError: Cannot read property 'Image' of undefined! </script>
If you're wondering why asynchronous loading is important, compare these two scenarios:
init
(no aync possible):init
required):Depending on synchronous XHR is not future-proof and makes the app significantly slower. As UI5 is getting better and better and preparing for further improvements, please keep following best-practices in order to "evolve" together with UI5.
Upvotes: 1